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 stdout.printf("cd %s; %s\n" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
229 Process.spawn_async_with_pipes (
233 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
243 //print(JSON.stringify(gret));
245 if (this.cfg.debug) {
247 stdout.printf("PID: %d\n" ,this.pid);
250 this.ref(); // additional ref - cleared on tidyup...
252 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
253 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
254 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
256 // make everything non-blocking!
260 // using NONBLOCKING only works if io_add_watch
261 //returns true/false in right conditions
262 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
263 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
264 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
269 ChildWatch.add (this.pid, this.on_child_watch);
276 // add handlers for output and stderr.
278 this.out_src = (int) this.out_ch.add_watch (
279 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
280 (channel, condition) => {
281 return this.read(channel);
282 //return this.out_ch != null ? this.read(this.out_ch) : true;
285 this.err_src = (int) this.err_ch.add_watch (
286 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
287 (channel, condition) => {
288 return this.read(channel);
289 //return this.err_ch != null ? this.read(this.err_ch) : true;
296 // child can exit before we get this far..
297 if (this.cfg.input != null) {
298 if (this.cfg.debug) print("Trying to call listeners");
300 this.write(this.cfg.input());
301 // this probably needs to be a bit smarter...
302 //but... let's close input now..
303 this.in_ch.shutdown(true);
317 // async - if running - return..
318 if (this.cfg.async && this.pid > -1) {
323 // start mainloop if not async..
326 //print("starting main loop");
327 //if (this.cfg.debug) {
330 this.ctx = new MainLoop ();
331 this.ctx.run(); // wait fore exit?
333 //print("main_loop done!");
335 this.tidyup(); // tidyup get's called in main loop.
339 if (this.cfg.exceptions && this.result != 0) {
340 var errstr = string.joinv(" ", this.cfg.args) + "\n";
341 errstr += this.output;
342 errstr += this.output.length > 0 ? "\n" : "";
343 errstr += this.stderr;
344 //print("Throwing execute error:%s\n", errstr);
345 throw new SpawnError.EXECUTE_ERROR(errstr);
346 //this.toString = function() { return this.stderr; };
347 ///throw new Exception this; // we throw self...
349 // finally throw, or return self..
354 void on_child_watch(GLib.Pid w_pid, int result) {
356 this.result = result;
357 if (this.cfg.debug) {
358 stdout.printf("child_watch_add : result:%d\n", result);
361 this.read(this.out_ch);
362 this.read(this.err_ch);
365 Process.close_pid(this.pid);
367 if (this.ctx != null) {
372 //print("child process done - running callback, then tidyup");
373 this.on_finished(this.result, this.output);
377 //print("DONE TIDYUP");
384 private void tidyup()
388 Process.close_pid(this.pid); // hopefully kills it..
392 if (this.in_ch != null) this.in_ch.shutdown(true);
393 if (this.out_ch != null) this.out_ch.shutdown(true);
394 if (this.err_ch != null) this.err_ch.shutdown(true);
396 // error shutting down
398 // blank out channels
402 // rmeove listeners !! important otherwise we kill the CPU
403 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
404 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
412 * write to stdin of process
413 * @arg str {String} string to write to stdin of process
414 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
416 private int write(string str) throws Error // write a line to
418 if (this.in_ch == null) {
419 return 0; // input is closed
421 //print("write: " + str);
422 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
425 var res = this.in_ch.write_chars(str.to_utf8(), out written);
427 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
429 if (res != GLib.IOStatus.NORMAL) {
430 throw new SpawnError.WRITE_ERROR("Write failed");
439 * read from pipe and call appropriate listerner and add to output or stderr string.
440 * @arg giochannel to read from.
443 private bool read(IOChannel ch)
445 string prop = (ch == this.out_ch) ? "output" : "stderr";
446 // print("prop: " + prop);
447 //print ("spawn.read: %s\n", prop);
449 //print(JSON.stringify(ch, null,4));
457 return false; // spawn complete + closed... can't read any more.
461 var cond = ch.get_buffer_condition();
462 //if ((cond & GLib.IOCondition.ERR) > 0) {
465 //if ((cond & GLib.IOCondition.IN) < 1) {
468 status = ch.read_line( out buffer, out len, out term_pos );
474 if (buffer == null) {
477 //print("got buffer of %s\n", buffer);
478 // print('status: ' +JSON.stringify(status));
479 // print(JSON.stringify(x));
481 case GLib.IOStatus.NORMAL:
485 //if (this.listeners[prop]) {
486 // this.listeners[prop].call(this, x.str_return);
488 if (ch == this.out_ch) {
489 this.output += buffer;
490 if (this.cfg.output != null) {
491 this.cfg.output( buffer);
494 this.stderr += buffer;
496 //_this[prop] += x.str_return;
497 //if (this.cfg.debug) {
498 // stdout.printf("%s : %s", prop , buffer);
500 if (this.cfg.async) {
502 if ( Gtk.events_pending()) {
503 Gtk.main_iteration();
507 //this.ctx.iteration(true);
509 case GLib.IOStatus.AGAIN:
510 //print("Should be called again.. waiting for more data..");
513 case GLib.IOStatus.ERROR:
514 case GLib.IOStatus.EOF:
522 //print("RETURNING");
523 return false; // allow it to be called again..
531 args: ['ls', '/tmp'],
534 } catch (e) { print(JSON.stringify(e)); }
536 var secs = (new Date()).getSeconds()
540 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
543 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }