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.
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,
251 Process.spawn_async_with_pipes (
255 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
265 //print(JSON.stringify(gret));
267 if (this.cfg.debug) {
269 GLib.debug("PID: %d\n" ,this.pid);
272 this.ref(); // additional ref - cleared on tidyup...
274 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
275 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
276 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
278 // make everything non-blocking!
282 // using NONBLOCKING only works if io_add_watch
283 //returns true/false in right conditions
284 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
285 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
286 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
291 ChildWatch.add (this.pid, this.on_child_watch);
298 // add handlers for output and stderr.
300 this.out_src = (int) this.out_ch.add_watch (
301 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
302 (channel, condition) => {
303 return this.read(channel);
304 //return this.out_ch != null ? this.read(this.out_ch) : true;
307 this.err_src = (int) this.err_ch.add_watch (
308 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
309 (channel, condition) => {
310 return this.read(channel);
311 //return this.err_ch != null ? this.read(this.err_ch) : true;
318 // child can exit before we get this far..
319 if (this.cfg.input != null) {
320 if (this.cfg.debug) GLib.debug("Trying to call listeners");
322 this.write(this.cfg.input());
323 // this probably needs to be a bit smarter...
324 //but... let's close input now..
325 this.in_ch.shutdown(true);
339 // async - if running - return..
340 if (this.cfg.async && this.pid > -1) {
345 // start mainloop if not async..
348 //print("starting main loop");
349 if (this.cfg.debug) {
350 GLib.debug("starting main loop");
352 this.ctx = new MainLoop ();
353 this.ctx.run(); // wait fore exit?
354 if (this.cfg.debug) {
355 GLib.debug(" main loop done");
357 //print("main_loop done!");
359 this.tidyup(); // tidyup get's called in main loop.
363 if (this.cfg.exceptions && this.result != 0) {
364 var errstr = string.joinv(" ", this.cfg.args) + "\n";
365 errstr += this.output;
366 errstr += this.output.length > 0 ? "\n" : "";
367 errstr += this.stderr;
368 //print("Throwing execute error:%s\n", errstr);
369 throw new SpawnError.EXECUTE_ERROR(errstr);
370 //this.toString = function() { return this.stderr; };
371 ///throw new Exception this; // we throw self...
373 // finally throw, or return self..
378 void on_child_watch(GLib.Pid w_pid, int result) {
380 this.result = result;
381 if (this.cfg.debug) {
382 stdout.printf("child_watch_add : result:%d\n", result);
385 this.read(this.out_ch);
386 this.read(this.err_ch);
389 Process.close_pid(this.pid);
391 if (this.ctx != null) {
396 //print("child process done - running callback, then tidyup");
397 this.on_finished(this.result, this.output + (this.output.length > 0 ? "\n" : "") + this.stderr);
401 //print("DONE TIDYUP");
408 private void tidyup()
410 if (this.cfg.debug) {
411 GLib.debug("tidyup");
416 Process.close_pid(this.pid); // hopefully kills it..
420 if (this.in_ch != null) this.in_ch.shutdown(true);
421 if (this.out_ch != null) this.out_ch.shutdown(true);
422 if (this.err_ch != null) this.err_ch.shutdown(true);
424 // error shutting down
426 // blank out channels
430 // rmeove listeners !! important otherwise we kill the CPU
431 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
432 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
440 * write to stdin of process
441 * @arg str {String} string to write to stdin of process
442 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
444 private int write(string str) throws Error // write a line to
446 if (this.in_ch == null) {
447 return 0; // input is closed
449 //print("write: " + str);
450 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
453 var res = this.in_ch.write_chars(str.to_utf8(), out written);
455 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
457 if (res != GLib.IOStatus.NORMAL) {
458 throw new SpawnError.WRITE_ERROR("Write failed");
467 * read from pipe and call appropriate listerner and add to output or stderr string.
468 * @arg giochannel to read from.
471 private bool read(IOChannel ch)
473 string prop = (ch == this.out_ch) ? "output" : "stderr";
474 // print("prop: " + prop);
475 //print ("spawn.read: %s\n", prop);
477 //print(JSON.stringify(ch, null,4));
485 return false; // spawn complete + closed... can't read any more.
489 var cond = ch.get_buffer_condition();
490 //if ((cond & GLib.IOCondition.ERR) > 0) {
493 //if ((cond & GLib.IOCondition.IN) < 1) {
496 status = ch.read_line( out buffer, out len, out term_pos );
502 if (buffer == null) {
505 //print("got buffer of %s\n", buffer);
506 // print('status: ' +JSON.stringify(status));
507 // print(JSON.stringify(x));
509 case GLib.IOStatus.NORMAL:
513 //if (this.listeners[prop]) {
514 // this.listeners[prop].call(this, x.str_return);
516 if (ch == this.out_ch) {
517 this.output += buffer;
518 if (this.cfg.output != null) {
519 this.cfg.output( buffer);
522 this.stderr += buffer;
524 //_this[prop] += x.str_return;
525 //if (this.cfg.debug) {
526 // stdout.printf("%s : %s", prop , buffer);
528 if (this.cfg.async) {
530 if ( Gtk.events_pending()) {
531 Gtk.main_iteration();
535 //this.ctx.iteration(true);
537 case GLib.IOStatus.AGAIN:
538 //print("Should be called again.. waiting for more data..");
541 case GLib.IOStatus.ERROR:
542 case GLib.IOStatus.EOF:
550 //print("RETURNING");
551 return false; // allow it to be called again..
559 args: ['ls', '/tmp'],
562 } catch (e) { print(JSON.stringify(e)); }
564 var secs = (new Date()).getSeconds()
568 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
571 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }