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,
98 public void setHandlers(
104 this.output = output;
105 this.stderr = stderr;
107 this.finish = finish;
113 public errordomain SpawnError {
122 * @param cfg {SpawnConfig} settings - see properties.
124 * @arg cwd {String} working directory. (defaults to home directory)
125 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
126 * @arg listeners {Object} (optional) handlers for output, stderr, input
127 * stderr/output both receive output line as argument
128 * input should return any standard input
129 * finish recieves result as argument.
130 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
131 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
132 * @arg exceptions {Boolean} throw exception on failure (default no)
133 * @arg debug {Boolean} print out what's going on.. (default no)
138 public class Spawn : Object
143 public Spawn(SpawnConfig cfg) throws Error
151 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
152 if (this.cfg.args.length < 0) {
153 throw new SpawnError.NO_ARGS("No arguments");
160 MainLoop ctx = null; // the mainloop ctx.
163 * @property output {String} resulting output
165 public string output;
167 * @property stderr {String} resulting output from stderr
169 public string stderr;
171 * @property result {Number} execution result.
175 * @property pid {Number} pid of child process (of false if it's not running)
179 * @property in_ch {GLib.IOChannel} input io channel
181 IOChannel in_ch = null;
183 * @property out_ch {GLib.IOChannel} output io channel
185 IOChannel out_ch = null;
187 * @property err_ch {GLib.IOChannel} stderr io channel
189 IOChannel err_ch = null;
191 * @property err_src {int} the watch for errors
196 * @property err_src {int} the watch for output
203 * Run the configured command.
204 * result is applied to object properties (eg. '?' or 'stderr')
205 * @returns {Object} self.
207 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
219 if (this.cfg.debug) {
220 stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
223 Process.spawn_async_with_pipes (
227 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
237 //print(JSON.stringify(gret));
239 if (this.cfg.debug) {
241 stdout.printf("PID: %d" ,this.pid);
244 this.ref(); // additional ref - cleared on tidyup...
246 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
247 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
248 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
250 // make everything non-blocking!
254 // using NONBLOCKING only works if io_add_watch
255 //returns true/false in right conditions
256 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
257 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
258 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
263 ChildWatch.add (this.pid, (w_pid, result) => {
265 this.result = result;
266 if (this.cfg.debug) {
267 stdout.printf("child_watch_add : result:%d ", result);
270 this.read(this.out_ch);
271 this.read(this.err_ch);
274 Process.close_pid(this.pid);
276 if (this.ctx != null) {
281 //print("DONE TIDYUP");
282 if (this.cfg.finish != null) {
283 this.cfg.finish(this.result);
292 // add handlers for output and stderr.
294 this.out_src = (int) this.out_ch.add_watch (
295 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
296 (channel, condition) => {
298 return this.out_ch != null ? this.read(this.out_ch) : false;
301 this.err_src = (int) this.err_ch.add_watch (
302 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
303 (channel, condition) => {
304 return this.read(this.err_ch);
311 // child can exit before we get this far..
312 if (this.cfg.input != null) {
313 if (this.cfg.debug) print("Trying to call listeners");
315 this.write(this.cfg.input());
316 // this probably needs to be a bit smarter...
317 //but... let's close input now..
318 this.in_ch.shutdown(true);
332 // async - if running - return..
333 if (this.cfg.async && this.pid > -1) {
337 // start mainloop if not async..
340 print("starting main loop");
341 //if (this.cfg.debug) {
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) {
354 throw new SpawnError.EXECUTE_ERROR(this.stderr);
355 //this.toString = function() { return this.stderr; };
356 ///throw new Exception this; // we throw self...
359 // finally throw, or return self..
367 private void tidyup()
371 Process.close_pid(this.pid); // hopefully kills it..
375 if (this.in_ch != null) this.in_ch.shutdown(true);
376 if (this.out_ch != null) this.out_ch.shutdown(true);
377 if (this.err_ch != null) this.err_ch.shutdown(true);
379 // error shutting donw.
381 // blank out channels
385 // rmeove listeners !! important otherwise we kill the CPU
386 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
387 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
395 * write to stdin of process
396 * @arg str {String} string to write to stdin of process
397 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
399 private int write(string str) throws Error // write a line to
401 if (this.in_ch == null) {
402 return 0; // input is closed
404 //print("write: " + str);
405 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
408 var res = this.in_ch.write_chars(str.to_utf8(), out written);
410 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
412 if (res != GLib.IOStatus.NORMAL) {
413 throw new SpawnError.WRITE_ERROR("Write failed");
422 * read from pipe and call appropriate listerner and add to output or stderr string.
423 * @arg giochannel to read from.
426 private bool read(IOChannel ch)
428 string prop = (ch == this.out_ch) ? "output" : "stderr";
429 // print("prop: " + prop);
432 //print(JSON.stringify(ch, null,4));
440 return false; // spawn complete + closed... can't read any more.
444 var cond = ch.get_buffer_condition();
445 if ((cond & GLib.IOCondition.ERR) > 0) {
448 if ((cond & GLib.IOCondition.IN) < 1) {
451 status = ch.read_line( out buffer, out len, out term_pos );
458 // print('status: ' +JSON.stringify(status));
459 // print(JSON.stringify(x));
461 case GLib.IOStatus.NORMAL:
465 //if (this.listeners[prop]) {
466 // this.listeners[prop].call(this, x.str_return);
468 if (ch == this.out_ch) {
469 this.output += buffer;
470 if (this.cfg.output != null) {
471 this.cfg.output( buffer);
474 this.stderr += buffer;
476 //_this[prop] += x.str_return;
477 //if (this.cfg.debug) {
478 stdout.printf("%s : %s", prop , buffer);
480 if (this.cfg.async) {
482 if ( Gtk.events_pending()) {
483 Gtk.main_iteration();
488 //this.ctx.iteration(true);
490 case GLib.IOStatus.AGAIN:
491 //print("Should be called again.. waiting for more data..");
494 case GLib.IOStatus.ERROR:
495 case GLib.IOStatus.EOF:
503 //print("RETURNING");
504 return false; // allow it to be called again..
512 args: ['ls', '/tmp'],
515 } catch (e) { print(JSON.stringify(e)); }
517 var secs = (new Date()).getSeconds()
521 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
524 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }