6 /// # valac --pkg gio-2.0 --pkg posix Spawn.vala -o /tmp/Spawn
9 ///using Gee; // for array list?
11 static int main (string[] args) {
12 // A reference to our file
14 var cfg = new SpawnConfig("", { "ls" } , { "" });
15 var spawn = new Spawn(cfg);
22 //var Gio = imports.gi.Gio;
23 //var GLib = imports.gi.GLib;
29 * Library to wrap GLib.spawn_async_with_pipes
34 *var output = new Spawn( SpawnConfig() {
35 cwd = "/home", // empty string to default to homedirectory.
38 ouput = (line) => { stdout.printf("%d\n", line); }
39 stderr = (line) => { stdout.printf("%d\n", line); }
40 input = () => { return "xxx"; }
45 public delegate void SpawnOutput(string line);
46 public delegate void SpawnErr(string line);
47 public delegate string SpawnInput();
51 public class SpawnConfig {
56 public bool exceptions; // fire exceptions.
57 public bool debug; // fire exceptions.
59 public SpawnOutput output;
60 public SpawnErr stderr;
61 public SpawnInput input;
63 public SpawnConfig(string cwd,
81 public void setOptions(
87 this.exceptions = exceptions;
90 public void setHandlers(
103 errordomain SpawnError {
109 * @param cfg {SpawnConfig} settings - see properties.
111 * @arg cwd {String} working directory. (defaults to home directory)
112 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
113 * @arg listeners {Object} (optional) handlers for output, stderr, input
114 * stderr/output both receive output line as argument
115 * input should return any standard input
116 * finish recieves result as argument.
117 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
118 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
119 * @arg exceptions {Boolean} throw exception on failure (default no)
120 * @arg debug {Boolean} print out what's going on.. (default no)
125 public class Spawn : Object
130 public Spawn(SpawnConfig cfg) throws Error
137 this.cfg.cwd = this.cfg.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
138 if (this.cfg.args.length < 0) {
139 throw new SpawnError.NO_ARGS("No arguments");
146 bool ctx = false; // the mainloop ctx.
149 * @property output {String} resulting output
153 * @property stderr {String} resulting output from stderr
157 * @property result {Number} execution result.
161 * @property pid {Number} pid of child process (of false if it's not running)
165 * @property in_ch {GLib.IOChannel} input io channel
167 IOChannel in_ch = null;
169 * @property out_ch {GLib.IOChannel} output io channel
171 IOChannel out_ch = null;
173 * @property err_ch {GLib.IOChannel} stderr io channel
175 IOChannel err_ch = null;
177 * @property err_src {int} the watch for errors
182 * @property err_src {int} the watch for output
189 * Run the configured command.
190 * result is applied to object properties (eg. 'output' or 'stderr')
191 * @returns {Object} self.
205 if (this.cfg.debug) {
206 stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
209 Process.spawn_async_with_pipes (
213 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
223 //print(JSON.stringify(gret));
225 if (this.cfg.debug) {
227 stdout.printf("PID: %d" ,this.pid);
230 ChildWatch.add (this.pid, (w_pid, result) => {
232 this.result = result;
233 if (this.cfg.debug) {
234 stdout.printf("child_watch_add : result:%d ", result);
237 this.read(this.out_ch);
238 this.read(this.err_ch);
241 Process.close_pid(this.pid);
247 //print("DONE TIDYUP");
248 if (this.cfg.finish) {
249 this.cfg.finish(this.result);
256 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
257 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
258 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
260 // make everything non-blocking!
264 // using NONBLOCKING only works if io_add_watch
265 //returns true/false in right conditions
266 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
267 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
268 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
272 // add handlers for output and stderr.
274 this.out_src = this.out_ch.add_watch (
275 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
276 (channel, condition) => {
277 return this.read(_this.out_ch);
280 this.err_src = this.err_ch.add_watch (
281 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
282 (channel, condition) => {
283 return this.read(_this.err_ch);
290 // child can exit before 1we get this far..
291 if (this.cfg.input != null) {
292 if (this.cfg.debug) print("Trying to call listeners");
294 this.write(this.cfg.input());
295 // this probably needs to be a bit smarter...
296 //but... let's close input now..
309 // async - if running - return..
310 if (this.cfg.async && this.pid > -1) {
314 // start mainloop if not async..
317 if (this.cfg.debug) {
318 print("starting main loop");
320 this.ctx = new MainLoop ();
321 loop.run(); // wait fore exit?
323 //print("main_loop done!");
325 this.tidyup(); // tidyup get's called in main loop.
328 if (this.cfg.exceptions && this.result != 0) {
329 //this.toString = function() { return this.stderr; };
330 ///throw new Exception this; // we throw self...
333 // finally throw, or return self..
341 private void tidyup()
344 Process.close_pid(this.pid); // hopefully kills it..
347 if (this.in_ch) this.in_ch.close();
348 if (this.out_ch) this.out_ch.close();
349 if (this.err_ch) this.err_ch.close();
350 // blank out channels
354 // rmeove listeners !! important otherwise we kill the CPU
355 if (this.err_src > -1 ) GLib.source_remove(this.err_src);
356 if (this.out_src > -1 ) GLib.source_remove(this.out_src);
364 * write to stdin of process
365 * @arg str {String} string to write to stdin of process
366 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
368 private int write(string str) // write a line to
370 if (this.in_ch == null) {
371 return 0; // input is closed
373 //print("write: " + str);
374 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
376 //var res = this.in_ch.write_chars(str, str.length, ret);
377 var res = this.in_ch.write_chars(str, str.length);
379 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
381 if (res != GLib.IOStatus.NORMAL) {
382 throw "Write failed";
390 * read from pipe and call appropriate listerner and add to output or stderr string.
391 * @arg giochannel to read from.
394 private bool read(IOChannel ch)
396 string prop = (ch == this.out_ch) ? "output" : "stderr";
397 // print("prop: " + prop);
401 //print(JSON.stringify(ch, null,4));
408 status = ch.read_line( out buffer, out len, out term_pos );
414 // print('status: ' +JSON.stringify(status));
415 // print(JSON.stringify(x));
417 case GLib.IOStatus.NORMAL:
420 if (this.listeners[prop]) {
421 this.listeners[prop].call(this, x.str_return);
423 _this[prop] += x.str_return;
425 print(prop + ':' + x.str_return.replace(/\n/, ''));
429 if (imports.gi.Gtk.events_pending()) {
430 imports.gi.Gtk.main_iteration();
437 //this.ctx.iteration(true);
439 case GLib.IOStatus.AGAIN:
440 //print("Should be called again.. waiting for more data..");
443 case GLib.IOStatus.ERROR:
444 case GLib.IOStatus.EOF:
452 //print("RETURNING");
453 return false; // allow it to be called again..
461 args: ['ls', '/tmp'],
464 } catch (e) { print(JSON.stringify(e)); }
466 var secs = (new Date()).getSeconds()
470 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
473 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }