4 /// # valac --pkg gio-2.0 --pkg posix Spawn.vala -o /tmp/Spawn
7 ///using Gee; // for array list?
9 static int main (string[] args) {
10 // A reference to our file
12 var cfg = new SpawnConfig(null, { "ls" } , "");
13 var spawn = new Spawn(cfg);
20 var Gio = imports.gi.Gio;
21 var GLib = imports.gi.GLib;
27 * Library to wrap GLib.spawn_async_with_pipes
32 *var output = new Spawn( SpawnConfig() {
33 cwd = "/home", // empty string to default to homedirectory.
36 ouput = (line) => { stdout.printf("%d\n", line); }
37 stderr = (line) => { stdout.printf("%d\n", line); }
38 input = () => { return "xxx"; }
43 delegate void SpawnOutput(string line);
44 delegate void SpawnErr(string line);
45 delegate string SpawnInput();
49 public class SpawnConfig {
54 public boolean exceptions; // fire exceptions.
55 public boolean debug; // fire exceptions.
57 public SpawnOutput output
58 public SpawnErr stderr;
59 public SpawnInput input;
61 public SpawnConfig(string cwd,
86 this.exceptions = exceptions;
104 * @param cfg {SpawnConfig} settings - see properties.
106 * @arg cwd {String} working directory. (defaults to home directory)
107 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
108 * @arg listeners {Object} (optional) handlers for output, stderr, input
109 * stderr/output both receive output line as argument
110 * input should return any standard input
111 * finish recieves result as argument.
112 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
113 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
114 * @arg exceptions {Boolean} throw exception on failure (default no)
115 * @arg debug {Boolean} print out what's going on.. (default no)
120 public class Spawn : Object
125 public Spawn(SpawnConfig cfg)
132 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
133 if (!this.cfg.args.length) {
134 throw "No arguments";
141 boolean ctx = false; // the mainloop ctx.
144 * @property output {String} resulting output
148 * @property stderr {String} resulting output from stderr
152 * @property result {Number} execution result.
156 * @property pid {Number} pid of child process (of false if it's not running)
160 * @property in_ch {GLib.IOChannel} input io channel
162 IOChannel in_ch = null;
164 * @property out_ch {GLib.IOChannel} output io channel
166 IOChannel out_ch = null;
168 * @property err_ch {GLib.IOChannel} stderr io channel
170 IOChannel err_ch = null;
172 * @property err_src {int} the watch for errors
177 * @property err_src {int} the watch for output
184 * Run the configured command.
185 * result is applied to object properties (eg. 'output' or 'stderr')
186 * @returns {Object} self.
201 if (this.cfg.debug) {
202 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
205 Process.spawn_async_with_pipes (
209 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
219 //print(JSON.stringify(gret));
221 if (this.cfg.debug) {
222 print("PID: " + this.pid);
225 ChildWatch.add (this.pid, (w_pid, result) => {
227 this.result = result;
229 print("child_watch_add : result: " + result);
232 this.read(this.out_ch);
233 this.read(this.err_ch);
236 Process.close_pid(this.pid);
242 //print("DONE TIDYUP");
243 if (this.cfg.finish) {
244 this.cfg.finish(this.result);
251 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
252 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
253 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
255 // make everything non-blocking!
259 // using NONBLOCKING only works if io_add_watch
260 //returns true/false in right conditions
261 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
262 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
263 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
267 // add handlers for output and stderr.
269 this.out_src = this.out_ch.add_watch (
270 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
271 (channel, condition) => {
272 return this.read(_this.out_ch);
275 this.err_src = this.err_ch.add_watch (
276 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
277 (channel, condition) => {
278 return this.read(_this.err_ch);
285 // child can exit before 1we get this far..
286 if (this.cfg.input != null) {
287 if (this.cfg.debug) print("Trying to call listeners");
289 this.write(this.cfg.input());
290 // this probably needs to be a bit smarter...
291 //but... let's close input now..
304 // async - if running - return..
305 if (this.cfg.async && this.pid > -1) {
309 // start mainloop if not async..
312 if (this.cfg.debug) {
313 print("starting main loop");
315 this.ctx = new MainLoop ();
316 loop.run(); // wait fore exit?
318 //print("main_loop done!");
320 this.tidyup(); // tidyup get's called in main loop.
323 if (this.cfg.exceptions && this.result != 0) {
324 //this.toString = function() { return this.stderr; };
325 ///throw new Exception this; // we throw self...
328 // finally throw, or return self..
336 private void tidyup()
339 Process.close_pid(this.pid); // hopefully kills it..
342 if (this.in_ch) this.in_ch.close();
343 if (this.out_ch) this.out_ch.close();
344 if (this.err_ch) this.err_ch.close();
345 // blank out channels
349 // rmeove listeners !! important otherwise we kill the CPU
350 if (this.err_src !== false) GLib.source_remove(this.err_src);
351 if (this.out_src !== false) GLib.source_remove(this.out_src);
352 this.err_src = false;
353 this.out_src = false;
359 * write to stdin of process
360 * @arg str {String} string to write to stdin of process
361 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
363 integer write(str) // write a line to
365 if (this.in_ch is null) {
366 return 0; // input is closed
368 //print("write: " + str);
369 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
371 //var res = this.in_ch.write_chars(str, str.length, ret);
372 var res = this.in_ch.write_chars(str, str.length);
374 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
376 if (res != GLib.IOStatus.NORMAL) {
377 throw "Write failed";
385 * read from pipe and call appropriate listerner and add to output or stderr string.
386 * @arg giochannel to read from.
391 var prop = ch == this.out_ch ? 'output' : 'stderr';
392 // print("prop: " + prop);
396 //print(JSON.stringify(ch, null,4));
400 var status = ch.read_line( x);
401 // print('status: ' +JSON.stringify(status));
402 // print(JSON.stringify(x));
404 case GLib.IOStatus.NORMAL:
407 if (this.listeners[prop]) {
408 this.listeners[prop].call(this, x.str_return);
410 _this[prop] += x.str_return;
412 print(prop + ':' + x.str_return.replace(/\n/, ''));
416 if (imports.gi.Gtk.events_pending()) {
417 imports.gi.Gtk.main_iteration();
424 //this.ctx.iteration(true);
426 case GLib.IOStatus.AGAIN:
427 //print("Should be called again.. waiting for more data..");
430 case GLib.IOStatus.ERROR:
431 case GLib.IOStatus.EOF:
439 //print("RETURNING");
440 return false; // allow it to be called again..
448 args: ['ls', '/tmp'],
451 } catch (e) { print(JSON.stringify(e)); }
453 var secs = (new Date()).getSeconds()
457 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
460 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }