2 /// # valac --pkg gio-2.0 --pkg gtk+-3.0 --pkg posix Spawn.vala -o /tmp/Spawn
10 ///using Gee; // for array list?
12 static int main (string[] args) {
13 // A reference to our file
15 var cfg = new SpawnConfig("", { "ls" } , { "" });
18 stdout.printf("%s\n", line);
23 false, // exceptions?? needed??
30 stdout.printf("Error %s", e.message);
37 //var Gio = imports.gi.Gio;
38 //var GLib = imports.gi.GLib;
44 * Library to wrap GLib.spawn_async_with_pipes
49 *var output = new Spawn( SpawnConfig() {
50 cwd = "/home", // empty string to default to homedirectory.
53 ouput = (line) => { stdout.printf("%d\n", line); }
54 stderr = (line) => { stdout.printf("%d\n", line); }
55 input = () => { return "xxx"; }
60 public delegate void SpawnOutput(string line);
61 public delegate void SpawnErr(string line);
62 public delegate string SpawnInput();
63 public delegate void SpawnFinish(int result, string output);
66 public class SpawnConfig {
71 public bool exceptions; // fire exceptions.
72 public bool debug; // fire exceptions.
74 public SpawnOutput output;
75 public SpawnErr stderr;
76 public SpawnInput input;
79 public SpawnConfig(string cwd,
99 public void setHandlers(
105 this.output = output;
106 this.stderr = stderr;
114 public errordomain SpawnError {
123 * @param cfg {SpawnConfig} settings - see properties.
125 * @arg cwd {String} working directory. (defaults to home directory)
126 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
127 * @arg listeners {Object} (optional) handlers for output, stderr, input
128 * stderr/output both receive output line as argument
129 * input should return any standard input
130 * finish recieves result as argument.
131 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
132 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
133 * @arg exceptions {Boolean} throw exception on failure (default no)
134 * @arg debug {Boolean} print out what's going on.. (default no)
139 public class Spawn : Object
144 public Spawn(SpawnConfig cfg) throws Error
152 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
153 if (this.cfg.args.length < 0) {
154 throw new SpawnError.NO_ARGS("No arguments");
156 if (!this.cfg.async) {
157 this.run((res, output) => { });
163 MainLoop ctx = null; // the mainloop ctx.
166 * @property output {String} resulting output
168 public string output;
170 * @property stderr {String} resulting output from stderr
172 public string stderr;
174 * @property result {Number} execution result.
176 public int result= 0;
178 * @property pid {Number} pid of child process (of false if it's not running)
182 * @property in_ch {GLib.IOChannel} input io channel
184 IOChannel in_ch = null;
186 * @property out_ch {GLib.IOChannel} output io channel
188 IOChannel out_ch = null;
190 * @property err_ch {GLib.IOChannel} stderr io channel
192 IOChannel err_ch = null;
194 * @property err_src {int} the watch for errors
199 * @property err_src {int} the watch for output
204 unowned SpawnFinish on_finished;
209 * Run the configured command.
210 * result is applied to object properties (eg. '?' or 'stderr')
211 * @returns {Object} self.
213 public void run( SpawnFinish finished_cb) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
216 this.on_finished = finished_cb;
225 if (this.cfg.debug) {
226 GLib.debug("cd %s; %s\n" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
230 if (!this.cfg.async) {
239 SpawnFlags.SEARCH_PATH,
245 this.output = ls_stdout;
246 this.stderr = ls_stderr;
247 this.result = ls_status;
248 if (this.cfg.exceptions && this.result != 0) {
249 var errstr = string.joinv(" ", this.cfg.args) + "\n";
250 errstr += this.output;
251 errstr += this.output.length > 0 ? "\n" : "";
252 errstr += this.stderr;
253 //print("Throwing execute error:%s\n", errstr);
254 throw new SpawnError.EXECUTE_ERROR(errstr);
255 //this.toString = function() { return this.stderr; };
256 ///throw new Exception this; // we throw self...
265 Process.spawn_async_with_pipes (
269 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
279 //print(JSON.stringify(gret));
281 if (this.cfg.debug) {
283 GLib.debug("PID: %d\n" ,this.pid);
286 this.ref(); // additional ref - cleared on tidyup...
288 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
289 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
290 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
292 // make everything non-blocking!
296 // using NONBLOCKING only works if io_add_watch
297 //returns true/false in right conditions
298 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
299 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
300 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
305 ChildWatch.add (this.pid, this.on_child_watch);
312 // add handlers for output and stderr.
314 this.out_src = (int) this.out_ch.add_watch (
315 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
316 (channel, condition) => {
317 return this.read(channel);
318 //return this.out_ch != null ? this.read(this.out_ch) : true;
321 this.err_src = (int) this.err_ch.add_watch (
322 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
323 (channel, condition) => {
324 return this.read(channel);
325 //return this.err_ch != null ? this.read(this.err_ch) : true;
332 // child can exit before we get this far..
333 if (this.cfg.input != null) {
334 if (this.cfg.debug) GLib.debug("Trying to call listeners");
336 this.write(this.cfg.input());
337 // this probably needs to be a bit smarter...
338 //but... let's close input now..
339 this.in_ch.shutdown(true);
353 // async - if running - return..
354 if (this.cfg.async && this.pid > -1) {
359 // start mainloop if not async..
362 //print("starting main loop");
363 if (this.cfg.debug) {
364 GLib.debug("starting main loop");
366 this.ctx = new MainLoop ();
367 this.ctx.run(); // wait fore exit?
368 if (this.cfg.debug) {
369 GLib.debug(" main loop done");
371 //print("main_loop done!");
373 this.tidyup(); // tidyup get's called in main loop.
377 if (this.cfg.exceptions && this.result != 0) {
378 var errstr = string.joinv(" ", this.cfg.args) + "\n";
379 errstr += this.output;
380 errstr += this.output.length > 0 ? "\n" : "";
381 errstr += this.stderr;
382 //print("Throwing execute error:%s\n", errstr);
383 throw new SpawnError.EXECUTE_ERROR(errstr);
384 //this.toString = function() { return this.stderr; };
385 ///throw new Exception this; // we throw self...
387 // finally throw, or return self..
392 void on_child_watch(GLib.Pid w_pid, int result) {
394 this.result = result;
395 if (this.cfg.debug) {
396 stdout.printf("child_watch_add : result:%d\n", result);
399 this.read(this.out_ch);
400 this.read(this.err_ch);
403 Process.close_pid(this.pid);
405 if (this.ctx != null) {
410 //print("child process done - running callback, then tidyup");
411 this.on_finished(this.result, this.output + (this.output.length > 0 ? "\n" : "") + this.stderr);
415 //print("DONE TIDYUP");
422 private void tidyup()
424 if (this.cfg.debug) {
425 GLib.debug("tidyup");
430 Process.close_pid(this.pid); // hopefully kills it..
434 if (this.in_ch != null) this.in_ch.shutdown(true);
435 if (this.out_ch != null) this.out_ch.shutdown(true);
436 if (this.err_ch != null) this.err_ch.shutdown(true);
438 // error shutting down
440 // blank out channels
444 // rmeove listeners !! important otherwise we kill the CPU
445 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
446 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
454 * write to stdin of process
455 * @arg str {String} string to write to stdin of process
456 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
458 private int write(string str) throws Error // write a line to
460 if (this.in_ch == null) {
461 return 0; // input is closed
463 //print("write: " + str);
464 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
467 var res = this.in_ch.write_chars(str.to_utf8(), out written);
469 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
471 if (res != GLib.IOStatus.NORMAL) {
472 throw new SpawnError.WRITE_ERROR("Write failed");
481 * read from pipe and call appropriate listerner and add to output or stderr string.
482 * @arg giochannel to read from.
485 private bool read(IOChannel ch)
487 string prop = (ch == this.out_ch) ? "output" : "stderr";
488 // print("prop: " + prop);
489 //print ("spawn.read: %s\n", prop);
491 //print(JSON.stringify(ch, null,4));
499 return false; // spawn complete + closed... can't read any more.
503 var cond = ch.get_buffer_condition();
504 //if ((cond & GLib.IOCondition.ERR) > 0) {
507 //if ((cond & GLib.IOCondition.IN) < 1) {
510 status = ch.read_line( out buffer, out len, out term_pos );
516 if (buffer == null) {
519 //print("got buffer of %s\n", buffer);
520 // print('status: ' +JSON.stringify(status));
521 // print(JSON.stringify(x));
523 case GLib.IOStatus.NORMAL:
527 //if (this.listeners[prop]) {
528 // this.listeners[prop].call(this, x.str_return);
530 if (ch == this.out_ch) {
531 this.output += buffer;
532 if (this.cfg.output != null) {
533 this.cfg.output( buffer);
536 this.stderr += buffer;
538 //_this[prop] += x.str_return;
539 //if (this.cfg.debug) {
540 // stdout.printf("%s : %s", prop , buffer);
542 if (this.cfg.async) {
544 if ( Gtk.events_pending()) {
545 Gtk.main_iteration();
549 //this.ctx.iteration(true);
551 case GLib.IOStatus.AGAIN:
552 //print("Should be called again.. waiting for more data..");
555 case GLib.IOStatus.ERROR:
556 case GLib.IOStatus.EOF:
564 //print("RETURNING");
565 return false; // allow it to be called again..
573 args: ['ls', '/tmp'],
576 } catch (e) { print(JSON.stringify(e)); }
578 var secs = (new Date()).getSeconds()
582 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
585 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }