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);
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;
77 public SpawnFinish finish;
79 public SpawnConfig(string cwd,
97 public void setOptions(
103 this.exceptions = exceptions;
106 public void setHandlers(
112 this.output = output;
113 this.stderr = stderr;
115 this.finish = finish;
121 public errordomain SpawnError {
130 * @param cfg {SpawnConfig} settings - see properties.
132 * @arg cwd {String} working directory. (defaults to home directory)
133 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
134 * @arg listeners {Object} (optional) handlers for output, stderr, input
135 * stderr/output both receive output line as argument
136 * input should return any standard input
137 * finish recieves result as argument.
138 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
139 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
140 * @arg exceptions {Boolean} throw exception on failure (default no)
141 * @arg debug {Boolean} print out what's going on.. (default no)
146 public class Spawn : Object
151 public Spawn(SpawnConfig cfg) throws Error
158 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
159 if (this.cfg.args.length < 0) {
160 throw new SpawnError.NO_ARGS("No arguments");
167 MainLoop ctx = null; // the mainloop ctx.
170 * @property output {String} resulting output
174 * @property stderr {String} resulting output from stderr
178 * @property result {Number} execution result.
182 * @property pid {Number} pid of child process (of false if it's not running)
186 * @property in_ch {GLib.IOChannel} input io channel
188 IOChannel in_ch = null;
190 * @property out_ch {GLib.IOChannel} output io channel
192 IOChannel out_ch = null;
194 * @property err_ch {GLib.IOChannel} stderr io channel
196 IOChannel err_ch = null;
198 * @property err_src {int} the watch for errors
203 * @property err_src {int} the watch for output
210 * Run the configured command.
211 * result is applied to object properties (eg. '?' or 'stderr')
212 * @returns {Object} self.
214 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
226 if (this.cfg.debug) {
227 stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
230 Process.spawn_async_with_pipes (
234 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
244 //print(JSON.stringify(gret));
246 if (this.cfg.debug) {
248 stdout.printf("PID: %d" ,this.pid);
251 ChildWatch.add (this.pid, (w_pid, result) => {
253 this.result = result;
254 if (this.cfg.debug) {
255 stdout.printf("child_watch_add : result:%d ", result);
258 this.read(this.out_ch);
259 this.read(this.err_ch);
262 Process.close_pid(this.pid);
264 if (this.ctx != null) {
269 //print("DONE TIDYUP");
270 if (this.cfg.finish != null) {
271 this.cfg.finish(this.result);
278 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
279 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
280 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
282 // make everything non-blocking!
286 // using NONBLOCKING only works if io_add_watch
287 //returns true/false in right conditions
288 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
289 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
290 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
294 // add handlers for output and stderr.
296 this.out_src = (int) this.out_ch.add_watch (
297 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
298 (channel, condition) => {
299 return this.read(this.out_ch);
302 this.err_src = (int) this.err_ch.add_watch (
303 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
304 (channel, condition) => {
305 return this.read(this.err_ch);
312 // child can exit before we get this far..
313 if (this.cfg.input != null) {
314 if (this.cfg.debug) print("Trying to call listeners");
316 this.write(this.cfg.input());
317 // this probably needs to be a bit smarter...
318 //but... let's close input now..
319 this.in_ch.shutdown(true);
333 // async - if running - return..
334 if (this.cfg.async && this.pid > -1) {
338 // start mainloop if not async..
341 if (this.cfg.debug) {
342 print("starting main loop");
344 this.ctx = new MainLoop ();
345 this.ctx.run(); // wait fore exit?
347 //print("main_loop done!");
349 this.tidyup(); // tidyup get's called in main loop.
352 if (this.cfg.exceptions && this.result != 0) {
353 //this.toString = function() { return this.stderr; };
354 ///throw new Exception this; // we throw self...
357 // finally throw, or return self..
365 private void tidyup()
368 Process.close_pid(this.pid); // hopefully kills it..
372 if (this.in_ch != null) this.in_ch.shutdown(true);
373 if (this.out_ch != null) this.out_ch.shutdown(true);
374 if (this.err_ch != null) this.err_ch.shutdown(true);
376 // error shutting donw.
378 // blank out channels
382 // rmeove listeners !! important otherwise we kill the CPU
383 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
384 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
392 * write to stdin of process
393 * @arg str {String} string to write to stdin of process
394 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
396 private int write(string str) throws Error // write a line to
398 if (this.in_ch == null) {
399 return 0; // input is closed
401 //print("write: " + str);
402 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
405 var res = this.in_ch.write_chars(str.to_utf8(), out written);
407 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
409 if (res != GLib.IOStatus.NORMAL) {
410 throw new SpawnError.WRITE_ERROR("Write failed");
418 * read from pipe and call appropriate listerner and add to output or stderr string.
419 * @arg giochannel to read from.
422 private bool read(IOChannel ch)
424 string prop = (ch == this.out_ch) ? "output" : "stderr";
425 // print("prop: " + prop);
428 //print(JSON.stringify(ch, null,4));
435 status = ch.read_line( out buffer, out len, out term_pos );
442 // print('status: ' +JSON.stringify(status));
443 // print(JSON.stringify(x));
445 case GLib.IOStatus.NORMAL:
449 //if (this.listeners[prop]) {
450 // this.listeners[prop].call(this, x.str_return);
452 if (ch == this.out_ch) {
453 this.output += buffer;
454 this.cfg.output( buffer);
456 this.stderr += buffer;
458 //_this[prop] += x.str_return;
459 if (this.cfg.debug) {
460 stdout.printf("%s : %s", prop , buffer);
462 if (this.cfg.async) {
464 if ( Gtk.events_pending()) {
465 Gtk.main_iteration();
470 //this.ctx.iteration(true);
472 case GLib.IOStatus.AGAIN:
473 //print("Should be called again.. waiting for more data..");
476 case GLib.IOStatus.ERROR:
477 case GLib.IOStatus.EOF:
485 //print("RETURNING");
486 return false; // allow it to be called again..
494 args: ['ls', '/tmp'],
497 } catch (e) { print(JSON.stringify(e)); }
499 var secs = (new Date()).getSeconds()
503 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
506 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }