3 ///using Gee; // for array list?
5 static int main (string[] args) {
6 // A reference to our file
8 var cfg = new SpawnConfig(null, { "ls" } , "");
9 var spawn = new Spawn(cfg);
16 var Gio = imports.gi.Gio;
17 var GLib = imports.gi.GLib;
23 * Library to wrap GLib.spawn_async_with_pipes
28 *var output = new Spawn( SpawnConfig() {
29 cwd = "/home", // empty string to default to homedirectory.
32 ouput = (line) => { stdout.printf("%d\n", line); }
33 stderr = (line) => { stdout.printf("%d\n", line); }
34 input = () => { return "xxx"; }
39 delegate void SpawnOutput(string line);
40 delegate void SpawnErr(string line);
41 delegate string SpawnInput();
45 public class SpawnConfig {
50 public boolean exceptions; // fire exceptions.
51 public boolean debug; // fire exceptions.
53 public SpawnOutput output
54 public SpawnErr stderr;
55 public SpawnInput input;
57 public SpawnConfig(string cwd,
82 this.exceptions = exceptions;
100 * @param cfg {SpawnConfig} settings - see properties.
102 * @arg cwd {String} working directory. (defaults to home directory)
103 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
104 * @arg listeners {Object} (optional) handlers for output, stderr, input
105 * stderr/output both receive output line as argument
106 * input should return any standard input
107 * finish recieves result as argument.
108 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
109 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
110 * @arg exceptions {Boolean} throw exception on failure (default no)
111 * @arg debug {Boolean} print out what's going on.. (default no)
116 public class Spawn : Object
121 public Spawn(SpawnConfig cfg)
128 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
129 if (!this.cfg.args.length) {
130 throw "No arguments";
137 boolean ctx = false; // the mainloop ctx.
140 * @property output {String} resulting output
144 * @property stderr {String} resulting output from stderr
148 * @property result {Number} execution result.
152 * @property pid {Number} pid of child process (of false if it's not running)
156 * @property in_ch {GLib.IOChannel} input io channel
158 IOChannel in_ch = null;
160 * @property out_ch {GLib.IOChannel} output io channel
162 IOChannel out_ch = null;
164 * @property err_ch {GLib.IOChannel} stderr io channel
166 IOChannel err_ch = null;
168 * @property err_src {int} the watch for errors
173 * @property err_src {int} the watch for output
180 * Run the configured command.
181 * result is applied to object properties (eg. 'output' or 'stderr')
182 * @returns {Object} self.
197 if (this.cfg.debug) {
198 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
201 Process.spawn_async_with_pipes (
205 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
215 //print(JSON.stringify(gret));
217 if (this.cfg.debug) {
218 print("PID: " + this.pid);
221 ChildWatch.add (this.pid, (w_pid, result) => {
223 this.result = result;
225 print("child_watch_add : result: " + result);
228 this.read(this.out_ch);
229 this.read(this.err_ch);
232 Process.close_pid(this.pid);
238 //print("DONE TIDYUP");
239 if (this.cfg.finish) {
240 this.cfg.finish(this.result);
247 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
248 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
249 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
251 // make everything non-blocking!
255 // using NONBLOCKING only works if io_add_watch
256 //returns true/false in right conditions
257 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
258 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
259 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
263 // add handlers for output and stderr.
265 this.out_src = this.out_ch.add_watch (
266 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
267 (channel, condition) => {
268 return this.read(_this.out_ch);
271 this.err_src = this.err_ch.add_watch (
272 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
273 (channel, condition) => {
274 return this.read(_this.err_ch);
281 // child can exit before 1we get this far..
282 if (this.cfg.input != null) {
283 if (this.cfg.debug) print("Trying to call listeners");
285 this.write(this.cfg.input());
286 // this probably needs to be a bit smarter...
287 //but... let's close input now..
300 // async - if running - return..
301 if (this.cfg.async && this.pid > -1) {
305 // start mainloop if not async..
308 if (this.cfg.debug) {
309 print("starting main loop");
311 this.ctx = new MainLoop ();
312 loop.run(); // wait fore exit?
314 //print("main_loop done!");
316 this.tidyup(); // tidyup get's called in main loop.
319 if (this.cfg.exceptions && this.result != 0) {
320 //this.toString = function() { return this.stderr; };
321 ///throw new Exception this; // we throw self...
324 // finally throw, or return self..
332 private void tidyup()
335 Process.close_pid(this.pid); // hopefully kills it..
338 if (this.in_ch) this.in_ch.close();
339 if (this.out_ch) this.out_ch.close();
340 if (this.err_ch) this.err_ch.close();
341 // blank out channels
345 // rmeove listeners !! important otherwise we kill the CPU
346 if (this.err_src !== false) GLib.source_remove(this.err_src);
347 if (this.out_src !== false) GLib.source_remove(this.out_src);
348 this.err_src = false;
349 this.out_src = false;
355 * write to stdin of process
356 * @arg str {String} string to write to stdin of process
357 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
359 integer write(str) // write a line to
361 if (this.in_ch is null) {
362 return 0; // input is closed
364 //print("write: " + str);
365 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
367 //var res = this.in_ch.write_chars(str, str.length, ret);
368 var res = this.in_ch.write_chars(str, str.length);
370 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
372 if (res != GLib.IOStatus.NORMAL) {
373 throw "Write failed";
381 * read from pipe and call appropriate listerner and add to output or stderr string.
382 * @arg giochannel to read from.
387 var prop = ch == this.out_ch ? 'output' : 'stderr';
388 // print("prop: " + prop);
392 //print(JSON.stringify(ch, null,4));
396 var status = ch.read_line( x);
397 // print('status: ' +JSON.stringify(status));
398 // print(JSON.stringify(x));
400 case GLib.IOStatus.NORMAL:
403 if (this.listeners[prop]) {
404 this.listeners[prop].call(this, x.str_return);
406 _this[prop] += x.str_return;
408 print(prop + ':' + x.str_return.replace(/\n/, ''));
412 if (imports.gi.Gtk.events_pending()) {
413 imports.gi.Gtk.main_iteration();
420 //this.ctx.iteration(true);
422 case GLib.IOStatus.AGAIN:
423 //print("Should be called again.. waiting for more data..");
426 case GLib.IOStatus.ERROR:
427 case GLib.IOStatus.EOF:
435 //print("RETURNING");
436 return false; // allow it to be called again..
444 args: ['ls', '/tmp'],
447 } catch (e) { print(JSON.stringify(e)); }
449 var secs = (new Date()).getSeconds()
453 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
456 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }