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("", { "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 public delegate void SpawnOutput(string line);
44 public delegate void SpawnErr(string line);
45 public delegate string SpawnInput();
49 public class SpawnConfig {
54 public bool exceptions; // fire exceptions.
55 public bool debug; // fire exceptions.
57 public SpawnOutput output;
58 public SpawnErr stderr;
59 public SpawnInput input;
61 public SpawnConfig(string cwd,
79 public void setOptions(
85 this.exceptions = exceptions;
88 public void setHandlers(
103 * @param cfg {SpawnConfig} settings - see properties.
105 * @arg cwd {String} working directory. (defaults to home directory)
106 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
107 * @arg listeners {Object} (optional) handlers for output, stderr, input
108 * stderr/output both receive output line as argument
109 * input should return any standard input
110 * finish recieves result as argument.
111 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
112 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
113 * @arg exceptions {Boolean} throw exception on failure (default no)
114 * @arg debug {Boolean} print out what's going on.. (default no)
119 public class Spawn : Object
124 public Spawn(SpawnConfig cfg) throws Error
131 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
132 if (!this.cfg.args.length) {
133 throw new Error("No arguments");
140 bool ctx = false; // the mainloop ctx.
143 * @property output {String} resulting output
147 * @property stderr {String} resulting output from stderr
151 * @property result {Number} execution result.
155 * @property pid {Number} pid of child process (of false if it's not running)
159 * @property in_ch {GLib.IOChannel} input io channel
161 IOChannel in_ch = null;
163 * @property out_ch {GLib.IOChannel} output io channel
165 IOChannel out_ch = null;
167 * @property err_ch {GLib.IOChannel} stderr io channel
169 IOChannel err_ch = null;
171 * @property err_src {int} the watch for errors
176 * @property err_src {int} the watch for output
183 * Run the configured command.
184 * result is applied to object properties (eg. 'output' or 'stderr')
185 * @returns {Object} self.
200 if (this.cfg.debug) {
201 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
204 Process.spawn_async_with_pipes (
208 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
218 //print(JSON.stringify(gret));
220 if (this.cfg.debug) {
221 print("PID: " + this.pid);
224 ChildWatch.add (this.pid, (w_pid, result) => {
226 this.result = result;
228 print("child_watch_add : result: " + result);
231 this.read(this.out_ch);
232 this.read(this.err_ch);
235 Process.close_pid(this.pid);
241 //print("DONE TIDYUP");
242 if (this.cfg.finish) {
243 this.cfg.finish(this.result);
250 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
251 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
252 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
254 // make everything non-blocking!
258 // using NONBLOCKING only works if io_add_watch
259 //returns true/false in right conditions
260 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
261 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
262 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
266 // add handlers for output and stderr.
268 this.out_src = this.out_ch.add_watch (
269 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
270 (channel, condition) => {
271 return this.read(_this.out_ch);
274 this.err_src = this.err_ch.add_watch (
275 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
276 (channel, condition) => {
277 return this.read(_this.err_ch);
284 // child can exit before 1we get this far..
285 if (this.cfg.input != null) {
286 if (this.cfg.debug) print("Trying to call listeners");
288 this.write(this.cfg.input());
289 // this probably needs to be a bit smarter...
290 //but... let's close input now..
303 // async - if running - return..
304 if (this.cfg.async && this.pid > -1) {
308 // start mainloop if not async..
311 if (this.cfg.debug) {
312 print("starting main loop");
314 this.ctx = new MainLoop ();
315 loop.run(); // wait fore exit?
317 //print("main_loop done!");
319 this.tidyup(); // tidyup get's called in main loop.
322 if (this.cfg.exceptions && this.result != 0) {
323 //this.toString = function() { return this.stderr; };
324 ///throw new Exception this; // we throw self...
327 // finally throw, or return self..
335 private void tidyup()
338 Process.close_pid(this.pid); // hopefully kills it..
341 if (this.in_ch) this.in_ch.close();
342 if (this.out_ch) this.out_ch.close();
343 if (this.err_ch) this.err_ch.close();
344 // blank out channels
348 // rmeove listeners !! important otherwise we kill the CPU
349 if (this.err_src > -1 ) GLib.source_remove(this.err_src);
350 if (this.out_src > -1 ) GLib.source_remove(this.out_src);
358 * write to stdin of process
359 * @arg str {String} string to write to stdin of process
360 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
362 private int write(string str) // write a line to
364 if (this.in_ch == null) {
365 return 0; // input is closed
367 //print("write: " + str);
368 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
370 //var res = this.in_ch.write_chars(str, str.length, ret);
371 var res = this.in_ch.write_chars(str, str.length);
373 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
375 if (res != GLib.IOStatus.NORMAL) {
376 throw "Write failed";
384 * read from pipe and call appropriate listerner and add to output or stderr string.
385 * @arg giochannel to read from.
388 private bool read(IOChannel ch)
390 string prop = (ch == this.out_ch) ? "output" : "stderr";
391 // print("prop: " + prop);
395 //print(JSON.stringify(ch, null,4));
399 var status = ch.read_line( x);
400 // print('status: ' +JSON.stringify(status));
401 // print(JSON.stringify(x));
403 case GLib.IOStatus.NORMAL:
406 if (this.listeners[prop]) {
407 this.listeners[prop].call(this, x.str_return);
409 _this[prop] += x.str_return;
411 print(prop + ':' + x.str_return.replace(/\n/, ''));
415 if (imports.gi.Gtk.events_pending()) {
416 imports.gi.Gtk.main_iteration();
423 //this.ctx.iteration(true);
425 case GLib.IOStatus.AGAIN:
426 //print("Should be called again.. waiting for more data..");
429 case GLib.IOStatus.ERROR:
430 case GLib.IOStatus.EOF:
438 //print("RETURNING");
439 return false; // allow it to be called again..
447 args: ['ls', '/tmp'],
450 } catch (e) { print(JSON.stringify(e)); }
452 var secs = (new Date()).getSeconds()
456 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
459 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }