3 ///using Gee; // for array list?
5 static int main (string[] args) {
6 // A reference to our file
7 var file = File.new_for_path ("data.txt");
13 var Gio = imports.gi.Gio;
14 var GLib = imports.gi.GLib;
20 * Library to wrap GLib.spawn_async_with_pipes
25 *var output = new Spawn( SpawnConfig() {
26 cwd = "/home", // empty string to default to homedirectory.
29 ouput = (line) => { stdout.printf("%d\n", line); }
30 stderr = (line) => { stdout.printf("%d\n", line); }
31 input = () => { return "xxx"; }
36 delegate void SpawnOutput(string line);
37 delegate void SpawnErr(string line);
38 delegate string SpawnInput();
42 public class SpawnConfig {
47 public boolean exceptions; // fire exceptions.
48 public boolean debug; // fire exceptions.
50 public SpawnOutput output
51 public SpawnErr stderr;
52 public SpawnInput input;
78 * @param cfg {SpawnConfig} settings - see properties.
80 * @arg cwd {String} working directory. (defaults to home directory)
81 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
82 * @arg listeners {Object} (optional) handlers for output, stderr, input
83 * stderr/output both receive output line as argument
84 * input should return any standard input
85 * finish recieves result as argument.
86 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
87 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
88 * @arg exceptions {Boolean} throw exception on failure (default no)
89 * @arg debug {Boolean} print out what's going on.. (default no)
94 public class Spawn : Object
99 public Spawn(SpawnConfig cfg)
106 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
107 if (!this.cfg.args.length) {
108 throw "No arguments";
115 boolean ctx = false; // the mainloop ctx.
118 * @property output {String} resulting output
122 * @property stderr {String} resulting output from stderr
126 * @property result {Number} execution result.
130 * @property pid {Number} pid of child process (of false if it's not running)
134 * @property in_ch {GLib.IOChannel} input io channel
136 IOChannel in_ch = null;
138 * @property out_ch {GLib.IOChannel} output io channel
140 IOChannel out_ch = null;
142 * @property err_ch {GLib.IOChannel} stderr io channel
144 IOChannel err_ch = null;
146 * @property err_src {int} the watch for errors
151 * @property err_src {int} the watch for output
158 * Run the configured command.
159 * result is applied to object properties (eg. 'output' or 'stderr')
160 * @returns {Object} self.
175 if (this.cfg.debug) {
176 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
179 Process.spawn_async_with_pipes (
183 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
193 //print(JSON.stringify(gret));
195 if (this.cfg.debug) {
196 print("PID: " + this.pid);
199 ChildWatch.add (this.pid, (w_pid, result) => {
201 this.result = result;
203 print("child_watch_add : result: " + result);
206 this.read(this.out_ch);
207 this.read(this.err_ch);
210 Process.close_pid(this.pid);
216 //print("DONE TIDYUP");
217 if (this.cfg.finish) {
218 this.cfg.finish(this.result);
225 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
226 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
227 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
229 // make everything non-blocking!
233 // using NONBLOCKING only works if io_add_watch
234 //returns true/false in right conditions
235 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
236 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
237 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
241 // add handlers for output and stderr.
243 this.out_src = this.out_ch.add_watch (
244 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
245 (channel, condition) => {
246 return this.read(_this.out_ch);
249 this.err_src = this.err_ch.add_watch (
250 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
251 (channel, condition) => {
252 return this.read(_this.err_ch);
259 // child can exit before 1we get this far..
260 if (this.cfg.input != null) {
261 if (this.cfg.debug) print("Trying to call listeners");
263 this.write(this.cfg.input());
264 // this probably needs to be a bit smarter...
265 //but... let's close input now..
278 // async - if running - return..
279 if (this.cfg.async && this.pid > -1) {
283 // start mainloop if not async..
286 if (this.cfg.debug) {
287 print("starting main loop");
289 this.ctx = new MainLoop ();
290 loop.run(); // wait fore exit?
292 //print("main_loop done!");
294 this.tidyup(); // tidyup get's called in main loop.
297 if (this.cfg.exceptions && this.result != 0) {
298 //this.toString = function() { return this.stderr; };
299 ///throw new Exception this; // we throw self...
302 // finally throw, or return self..
310 private void tidyup()
313 Process.close_pid(this.pid); // hopefully kills it..
316 if (this.in_ch) this.in_ch.close();
317 if (this.out_ch) this.out_ch.close();
318 if (this.err_ch) this.err_ch.close();
319 // blank out channels
323 // rmeove listeners !! important otherwise we kill the CPU
324 if (this.err_src !== false) GLib.source_remove(this.err_src);
325 if (this.out_src !== false) GLib.source_remove(this.out_src);
326 this.err_src = false;
327 this.out_src = false;
333 * write to stdin of process
334 * @arg str {String} string to write to stdin of process
335 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
337 integer write(str) // write a line to
339 if (this.in_ch is null) {
340 return 0; // input is closed
342 //print("write: " + str);
343 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
345 //var res = this.in_ch.write_chars(str, str.length, ret);
346 var res = this.in_ch.write_chars(str, str.length);
348 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
350 if (res != GLib.IOStatus.NORMAL) {
351 throw "Write failed";
359 * read from pipe and call appropriate listerner and add to output or stderr string.
360 * @arg giochannel to read from.
365 var prop = ch == this.out_ch ? 'output' : 'stderr';
366 // print("prop: " + prop);
370 //print(JSON.stringify(ch, null,4));
374 var status = ch.read_line( x);
375 // print('status: ' +JSON.stringify(status));
376 // print(JSON.stringify(x));
378 case GLib.IOStatus.NORMAL:
381 if (this.listeners[prop]) {
382 this.listeners[prop].call(this, x.str_return);
384 _this[prop] += x.str_return;
386 print(prop + ':' + x.str_return.replace(/\n/, ''));
390 if (imports.gi.Gtk.events_pending()) {
391 imports.gi.Gtk.main_iteration();
398 //this.ctx.iteration(true);
400 case GLib.IOStatus.AGAIN:
401 //print("Should be called again.. waiting for more data..");
404 case GLib.IOStatus.ERROR:
405 case GLib.IOStatus.EOF:
413 //print("RETURNING");
414 return false; // allow it to be called again..
422 args: ['ls', '/tmp'],
425 } catch (e) { print(JSON.stringify(e)); }
427 var secs = (new Date()).getSeconds()
431 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
434 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }