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) {
248 //print("DONE TIDYUP");
249 if (this.cfg.finish) {
250 this.cfg.finish(this.result);
257 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
258 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
259 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
261 // make everything non-blocking!
265 // using NONBLOCKING only works if io_add_watch
266 //returns true/false in right conditions
267 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
268 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
269 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
273 // add handlers for output and stderr.
275 this.out_src = this.out_ch.add_watch (
276 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
277 (channel, condition) => {
278 return this.read(_this.out_ch);
281 this.err_src = this.err_ch.add_watch (
282 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
283 (channel, condition) => {
284 return this.read(_this.err_ch);
291 // child can exit before 1we get this far..
292 if (this.cfg.input != null) {
293 if (this.cfg.debug) print("Trying to call listeners");
295 this.write(this.cfg.input());
296 // this probably needs to be a bit smarter...
297 //but... let's close input now..
310 // async - if running - return..
311 if (this.cfg.async && this.pid > -1) {
315 // start mainloop if not async..
318 if (this.cfg.debug) {
319 print("starting main loop");
321 this.ctx = new MainLoop ();
322 loop.run(); // wait fore exit?
324 //print("main_loop done!");
326 this.tidyup(); // tidyup get's called in main loop.
329 if (this.cfg.exceptions && this.result != 0) {
330 //this.toString = function() { return this.stderr; };
331 ///throw new Exception this; // we throw self...
334 // finally throw, or return self..
342 private void tidyup()
345 Process.close_pid(this.pid); // hopefully kills it..
348 if (this.in_ch) this.in_ch.close();
349 if (this.out_ch) this.out_ch.close();
350 if (this.err_ch) this.err_ch.close();
351 // blank out channels
355 // rmeove listeners !! important otherwise we kill the CPU
356 if (this.err_src > -1 ) GLib.source_remove(this.err_src);
357 if (this.out_src > -1 ) GLib.source_remove(this.out_src);
365 * write to stdin of process
366 * @arg str {String} string to write to stdin of process
367 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
369 private int write(string str) // write a line to
371 if (this.in_ch == null) {
372 return 0; // input is closed
374 //print("write: " + str);
375 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
377 //var res = this.in_ch.write_chars(str, str.length, ret);
378 var res = this.in_ch.write_chars(str, str.length);
380 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
382 if (res != GLib.IOStatus.NORMAL) {
383 throw "Write failed";
391 * read from pipe and call appropriate listerner and add to output or stderr string.
392 * @arg giochannel to read from.
395 private bool read(IOChannel ch)
397 string prop = (ch == this.out_ch) ? "output" : "stderr";
398 // print("prop: " + prop);
402 //print(JSON.stringify(ch, null,4));
409 status = ch.read_line( out buffer, out len, out term_pos );
415 // print('status: ' +JSON.stringify(status));
416 // print(JSON.stringify(x));
418 case GLib.IOStatus.NORMAL:
421 //if (this.listeners[prop]) {
422 // this.listeners[prop].call(this, x.str_return);
424 if (ch == this.out_ch) {
425 this.output += buffer;
427 this.stderr += buffer;
429 //_this[prop] += x.str_return;
430 if (this.cfg.debug) {
431 stdout.printf("%s : %s", prop , str_return);
433 if (this.cfg.async) {
435 if ( Gtk.events_pending()) {
436 Gtk.main_iteration();
443 //this.ctx.iteration(true);
445 case GLib.IOStatus.AGAIN:
446 //print("Should be called again.. waiting for more data..");
449 case GLib.IOStatus.ERROR:
450 case GLib.IOStatus.EOF:
458 //print("RETURNING");
459 return false; // allow it to be called again..
467 args: ['ls', '/tmp'],
470 } catch (e) { print(JSON.stringify(e)); }
472 var secs = (new Date()).getSeconds()
476 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
479 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }