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" } , { "" });
16 var spawn = new Spawn(cfg);
23 //var Gio = imports.gi.Gio;
24 //var GLib = imports.gi.GLib;
30 * Library to wrap GLib.spawn_async_with_pipes
35 *var output = new Spawn( SpawnConfig() {
36 cwd = "/home", // empty string to default to homedirectory.
39 ouput = (line) => { stdout.printf("%d\n", line); }
40 stderr = (line) => { stdout.printf("%d\n", line); }
41 input = () => { return "xxx"; }
46 public delegate void SpawnOutput(string line);
47 public delegate void SpawnErr(string line);
48 public delegate string SpawnInput();
52 public class SpawnConfig {
57 public bool exceptions; // fire exceptions.
58 public bool debug; // fire exceptions.
60 public SpawnOutput output;
61 public SpawnErr stderr;
62 public SpawnInput input;
64 public SpawnConfig(string cwd,
82 public void setOptions(
88 this.exceptions = exceptions;
91 public void setHandlers(
104 errordomain SpawnError {
110 * @param cfg {SpawnConfig} settings - see properties.
112 * @arg cwd {String} working directory. (defaults to home directory)
113 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
114 * @arg listeners {Object} (optional) handlers for output, stderr, input
115 * stderr/output both receive output line as argument
116 * input should return any standard input
117 * finish recieves result as argument.
118 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
119 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
120 * @arg exceptions {Boolean} throw exception on failure (default no)
121 * @arg debug {Boolean} print out what's going on.. (default no)
126 public class Spawn : Object
131 public Spawn(SpawnConfig cfg) throws Error
138 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
139 if (this.cfg.args.length < 0) {
140 throw new SpawnError.NO_ARGS("No arguments");
147 MainLoop ctx = null; // the mainloop ctx.
150 * @property output {String} resulting output
154 * @property stderr {String} resulting output from stderr
158 * @property result {Number} execution result.
162 * @property pid {Number} pid of child process (of false if it's not running)
166 * @property in_ch {GLib.IOChannel} input io channel
168 IOChannel in_ch = null;
170 * @property out_ch {GLib.IOChannel} output io channel
172 IOChannel out_ch = null;
174 * @property err_ch {GLib.IOChannel} stderr io channel
176 IOChannel err_ch = null;
178 * @property err_src {int} the watch for errors
183 * @property err_src {int} the watch for output
190 * Run the configured command.
191 * result is applied to object properties (eg. 'output' or 'stderr')
192 * @returns {Object} self.
206 if (this.cfg.debug) {
207 stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
210 Process.spawn_async_with_pipes (
214 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
224 //print(JSON.stringify(gret));
226 if (this.cfg.debug) {
228 stdout.printf("PID: %d" ,this.pid);
231 ChildWatch.add (this.pid, (w_pid, result) => {
233 this.result = result;
234 if (this.cfg.debug) {
235 stdout.printf("child_watch_add : result:%d ", result);
238 this.read(this.out_ch);
239 this.read(this.err_ch);
242 Process.close_pid(this.pid);
244 if (this.ctx != null) {
249 //print("DONE TIDYUP");
250 if (this.cfg.finish) {
251 this.cfg.finish(this.result);
258 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
259 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
260 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
262 // make everything non-blocking!
266 // using NONBLOCKING only works if io_add_watch
267 //returns true/false in right conditions
268 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
269 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
270 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
274 // add handlers for output and stderr.
276 this.out_src = this.out_ch.add_watch (
277 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
278 (channel, condition) => {
279 return this.read(_this.out_ch);
282 this.err_src = this.err_ch.add_watch (
283 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
284 (channel, condition) => {
285 return this.read(_this.err_ch);
292 // child can exit before 1we get this far..
293 if (this.cfg.input != null) {
294 if (this.cfg.debug) print("Trying to call listeners");
296 this.write(this.cfg.input());
297 // this probably needs to be a bit smarter...
298 //but... let's close input now..
311 // async - if running - return..
312 if (this.cfg.async && this.pid > -1) {
316 // start mainloop if not async..
319 if (this.cfg.debug) {
320 print("starting main loop");
322 this.ctx = new MainLoop ();
323 loop.run(); // wait fore exit?
325 //print("main_loop done!");
327 this.tidyup(); // tidyup get's called in main loop.
330 if (this.cfg.exceptions && this.result != 0) {
331 //this.toString = function() { return this.stderr; };
332 ///throw new Exception this; // we throw self...
335 // finally throw, or return self..
343 private void tidyup()
346 Process.close_pid(this.pid); // hopefully kills it..
349 if (this.in_ch != null) this.in_ch.shutdown(true);
350 if (this.out_ch != null) this.out_ch.shutdown(true);
351 if (this.err_ch != null) this.err_ch.shutdown(true);
352 // blank out channels
356 // rmeove listeners !! important otherwise we kill the CPU
357 if (this.err_src > -1 ) GLib.source_remove(this.err_src);
358 if (this.out_src > -1 ) GLib.source_remove(this.out_src);
366 * write to stdin of process
367 * @arg str {String} string to write to stdin of process
368 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
370 private int write(string str) // write a line to
372 if (this.in_ch == null) {
373 return 0; // input is closed
375 //print("write: " + str);
376 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
378 //var res = this.in_ch.write_chars(str, str.length, ret);
379 var res = this.in_ch.write_chars(str, str.length);
381 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
383 if (res != GLib.IOStatus.NORMAL) {
384 throw "Write failed";
392 * read from pipe and call appropriate listerner and add to output or stderr string.
393 * @arg giochannel to read from.
396 private bool read(IOChannel ch)
398 string prop = (ch == this.out_ch) ? "output" : "stderr";
399 // print("prop: " + prop);
403 //print(JSON.stringify(ch, null,4));
410 status = ch.read_line( out buffer, out len, out term_pos );
416 // print('status: ' +JSON.stringify(status));
417 // print(JSON.stringify(x));
419 case GLib.IOStatus.NORMAL:
422 //if (this.listeners[prop]) {
423 // this.listeners[prop].call(this, x.str_return);
425 if (ch == this.out_ch) {
426 this.output += buffer;
428 this.stderr += buffer;
430 //_this[prop] += x.str_return;
431 if (this.cfg.debug) {
432 stdout.printf("%s : %s", prop , str_return);
434 if (this.cfg.async) {
436 if ( Gtk.events_pending()) {
437 Gtk.main_iteration();
444 //this.ctx.iteration(true);
446 case GLib.IOStatus.AGAIN:
447 //print("Should be called again.. waiting for more data..");
450 case GLib.IOStatus.ERROR:
451 case GLib.IOStatus.EOF:
459 //print("RETURNING");
460 return false; // allow it to be called again..
468 args: ['ls', '/tmp'],
471 } catch (e) { print(JSON.stringify(e)); }
473 var secs = (new Date()).getSeconds()
477 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
480 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }