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,
97 public void onFinish( SpawnFinish? finish ) {
102 public void setHandlers(
108 this.output = output;
109 this.stderr = stderr;
117 public errordomain SpawnError {
126 * @param cfg {SpawnConfig} settings - see properties.
128 * @arg cwd {String} working directory. (defaults to home directory)
129 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
130 * @arg listeners {Object} (optional) handlers for output, stderr, input
131 * stderr/output both receive output line as argument
132 * input should return any standard input
133 * finish recieves result as argument.
134 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
135 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
136 * @arg exceptions {Boolean} throw exception on failure (default no)
137 * @arg debug {Boolean} print out what's going on.. (default no)
142 public class Spawn : Object
147 public Spawn(SpawnConfig cfg) throws Error
155 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
156 if (this.cfg.args.length < 0) {
157 throw new SpawnError.NO_ARGS("No arguments");
159 if (!this.cfg.async) {
160 this.run((res, output) => { });
166 MainLoop ctx = null; // the mainloop ctx.
169 * @property output {String} resulting output
171 public string output;
173 * @property stderr {String} resulting output from stderr
175 public string stderr;
177 * @property result {Number} execution result.
181 * @property pid {Number} pid of child process (of false if it's not running)
185 * @property in_ch {GLib.IOChannel} input io channel
187 IOChannel in_ch = null;
189 * @property out_ch {GLib.IOChannel} output io channel
191 IOChannel out_ch = null;
193 * @property err_ch {GLib.IOChannel} stderr io channel
195 IOChannel err_ch = null;
197 * @property err_src {int} the watch for errors
202 * @property err_src {int} the watch for output
209 * Run the configured command.
210 * result is applied to object properties (eg. '?' or 'stderr')
211 * @returns {Object} self.
213 public void run(unowned SpawnFinish finished_cb) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
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, (w_pid, result) => {
271 this.result = result;
272 if (this.cfg.debug) {
273 stdout.printf("child_watch_add : result:%d\n", result);
276 this.read(this.out_ch);
277 this.read(this.err_ch);
280 Process.close_pid(this.pid);
282 if (this.ctx != null) {
287 //print("DONE TIDYUP");
288 if (this.cfg.finish != null) {
289 this.cfg.finish(this.result);
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) print("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) {
344 // start mainloop if not async..
347 //print("starting main loop");
348 //if (this.cfg.debug) {
351 this.ctx = MainLoop ();
352 this.ctx.run(); // wait fore exit?
354 //print("main_loop done!");
356 this.tidyup(); // tidyup get's called in main loop.
360 if (this.cfg.exceptions && this.result != 0) {
361 var errstr = string.joinv(" ", this.cfg.args) + "\n";
362 errstr += this.output;
363 errstr += this.output.length > 0 ? "\n" : "";
364 errstr += this.stderr;
365 //print("Throwing execute error:%s\n", errstr);
366 throw SpawnError.EXECUTE_ERROR(errstr);
367 //this.toString = function() { return this.stderr; };
368 ///throw new Exception this; // we throw self...
370 // finally throw, or return self..
375 private void tidyup()
379 Process.close_pid(this.pid); // hopefully kills it..
383 if (this.in_ch != null) this.in_ch.shutdown(true);
384 if (this.out_ch != null) this.out_ch.shutdown(true);
385 if (this.err_ch != null) this.err_ch.shutdown(true);
387 // error shutting down
389 // blank out channels
393 // rmeove listeners !! important otherwise we kill the CPU
394 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
395 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
403 * write to stdin of process
404 * @arg str {String} string to write to stdin of process
405 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
407 private int write(string str) throws Error // write a line to
409 if (this.in_ch == null) {
410 return 0; // input is closed
412 //print("write: " + str);
413 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
416 var res = this.in_ch.write_chars(str.to_utf8(), out written);
418 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
420 if (res != GLib.IOStatus.NORMAL) {
421 throw new SpawnError.WRITE_ERROR("Write failed");
430 * read from pipe and call appropriate listerner and add to output or stderr string.
431 * @arg giochannel to read from.
434 private bool read(IOChannel ch)
436 string prop = (ch == this.out_ch) ? "output" : "stderr";
437 // print("prop: " + prop);
438 //print ("spawn.read: %s\n", prop);
440 //print(JSON.stringify(ch, null,4));
448 return false; // spawn complete + closed... can't read any more.
452 var cond = ch.get_buffer_condition();
453 //if ((cond & GLib.IOCondition.ERR) > 0) {
456 //if ((cond & GLib.IOCondition.IN) < 1) {
459 status = ch.read_line( out buffer, out len, out term_pos );
465 if (buffer == null) {
468 //print("got buffer of %s\n", buffer);
469 // print('status: ' +JSON.stringify(status));
470 // print(JSON.stringify(x));
472 case GLib.IOStatus.NORMAL:
476 //if (this.listeners[prop]) {
477 // this.listeners[prop].call(this, x.str_return);
479 if (ch == this.out_ch) {
480 this.output += buffer;
481 if (this.cfg.output != null) {
482 this.cfg.output( buffer);
485 this.stderr += buffer;
487 //_this[prop] += x.str_return;
488 //if (this.cfg.debug) {
489 // stdout.printf("%s : %s", prop , buffer);
491 if (this.cfg.async) {
493 if ( Gtk.events_pending()) {
494 Gtk.main_iteration();
498 //this.ctx.iteration(true);
500 case GLib.IOStatus.AGAIN:
501 //print("Should be called again.. waiting for more data..");
504 case GLib.IOStatus.ERROR:
505 case GLib.IOStatus.EOF:
513 //print("RETURNING");
514 return false; // allow it to be called again..
522 args: ['ls', '/tmp'],
525 } catch (e) { print(JSON.stringify(e)); }
527 var secs = (new Date()).getSeconds()
531 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
534 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }