2 /// # valac --pkg gio-2.0 --pkg gtk+-3.0 --pkg posix Spawn.vala -o /tmp/Spawn
10 * x = new Spawn( working dir, args)
11 * x.env = ..... (if you need to set one...
12 * x.output_line.connect((string str) => { ... });
13 * x.input_line.connect(() => { return string });
14 * x.finish.connect((int res, string output, string stderr) => { ... });
27 public errordomain SpawnError {
36 * @param cfg {SpawnConfig} settings - see properties.
38 * @arg cwd {String} working directory. (defaults to home directory)
39 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
40 * @arg listeners {Object} (optional) handlers for output, stderr, input
41 * stderr/output both receive output line as argument
42 * input should return any standard input
43 * finish recieves result as argument.
44 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
45 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
46 * @arg exceptions {Boolean} throw exception on failure (default no)
47 * @arg debug {Boolean} print out what's going on.. (default no)
52 public class Spawn : Object
54 public signal string input();
55 public signal void output_line(string str);
56 public signal void finish(int res, string str, string stderr);
61 public bool debug = false;
63 public Spawn(string cwd, string[] args) throws Error
74 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
75 if (this.args.length < 0) {
76 throw new SpawnError.NO_ARGS("No arguments");
83 MainLoop ctx = null; // the mainloop ctx.
86 * @property output {String} resulting output
90 * @property stderr {String} resulting output from stderr
94 * @property result {Number} execution result.
98 * @property pid {Number} pid of child process (of false if it's not running)
102 * @property in_ch {GLib.IOChannel} input io channel
104 IOChannel in_ch = null;
106 * @property out_ch {GLib.IOChannel} output io channel
108 IOChannel out_ch = null;
110 * @property err_ch {GLib.IOChannel} stderr io channel
112 IOChannel err_ch = null;
114 * @property err_src {int} the watch for errors
119 * @property err_src {int} the watch for output
126 * Run the configured command.
127 * result is applied to object properties (eg. '?' or 'stderr')
128 * @returns {Object} self.
130 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
143 Glib.debug("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
146 Process.spawn_async_with_pipes (
150 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
160 //print(JSON.stringify(gret));
162 if (this.cfg.debug) {
164 stdout.printf("PID: %d" ,this.pid);
167 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
168 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
169 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
171 // make everything non-blocking!
175 // using NONBLOCKING only works if io_add_watch
176 //returns true/false in right conditions
177 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
178 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
179 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
184 ChildWatch.add (this.pid, (w_pid, result) => {
186 this.result = result;
187 if (this.cfg.debug) {
188 stdout.printf("child_watch_add : result:%d ", result);
191 this.read(this.out_ch);
192 this.read(this.err_ch);
195 Process.close_pid(this.pid);
197 if (this.ctx != null) {
202 //print("DONE TIDYUP");
203 if (this.cfg.finish != null) {
204 this.cfg.finish(this.result);
213 // add handlers for output and stderr.
215 this.out_src = (int) this.out_ch.add_watch (
216 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
217 (channel, condition) => {
218 return this.read(this.out_ch);
221 this.err_src = (int) this.err_ch.add_watch (
222 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
223 (channel, condition) => {
224 return this.read(this.err_ch);
231 // child can exit before we get this far..
232 if (this.cfg.input != null) {
233 if (this.cfg.debug) print("Trying to call listeners");
235 this.write(this.cfg.input());
236 // this probably needs to be a bit smarter...
237 //but... let's close input now..
238 this.in_ch.shutdown(true);
252 // async - if running - return..
253 if (this.cfg.async && this.pid > -1) {
257 // start mainloop if not async..
260 print("starting main loop");
261 //if (this.cfg.debug) {
264 this.ctx = new MainLoop ();
265 this.ctx.run(); // wait fore exit?
267 print("main_loop done!");
269 this.tidyup(); // tidyup get's called in main loop.
272 if (this.cfg.exceptions && this.result != 0) {
274 throw new SpawnError.EXECUTE_ERROR(this.stderr);
275 //this.toString = function() { return this.stderr; };
276 ///throw new Exception this; // we throw self...
279 // finally throw, or return self..
287 private void tidyup()
290 Process.close_pid(this.pid); // hopefully kills it..
294 if (this.in_ch != null) this.in_ch.shutdown(true);
295 if (this.out_ch != null) this.out_ch.shutdown(true);
296 if (this.err_ch != null) this.err_ch.shutdown(true);
298 // error shutting donw.
300 // blank out channels
304 // rmeove listeners !! important otherwise we kill the CPU
305 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
306 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
314 * write to stdin of process
315 * @arg str {String} string to write to stdin of process
316 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
318 private int write(string str) throws Error // write a line to
320 if (this.in_ch == null) {
321 return 0; // input is closed
323 //print("write: " + str);
324 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
327 var res = this.in_ch.write_chars(str.to_utf8(), out written);
329 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
331 if (res != GLib.IOStatus.NORMAL) {
332 throw new SpawnError.WRITE_ERROR("Write failed");
342 * read from pipe and call appropriate listerner and add to output or stderr string.
343 * @arg giochannel to read from.
346 private bool read(IOChannel ch)
348 string prop = (ch == this.out_ch) ? "output" : "stderr";
349 // print("prop: " + prop);
352 //print(JSON.stringify(ch, null,4));
359 status = ch.read_line( out buffer, out len, out term_pos );
366 // print('status: ' +JSON.stringify(status));
367 // print(JSON.stringify(x));
369 case GLib.IOStatus.NORMAL:
373 //if (this.listeners[prop]) {
374 // this.listeners[prop].call(this, x.str_return);
376 if (ch == this.out_ch) {
377 this.output += buffer;
378 if (this.cfg.output != null) {
379 this.cfg.output( buffer);
382 this.stderr += buffer;
384 //_this[prop] += x.str_return;
385 //if (this.cfg.debug) {
386 stdout.printf("%s : %s", prop , buffer);
388 if (this.cfg.async) {
390 if ( Gtk.events_pending()) {
391 Gtk.main_iteration();
396 //this.ctx.iteration(true);
398 case GLib.IOStatus.AGAIN:
399 //print("Should be called again.. waiting for more data..");
402 case GLib.IOStatus.ERROR:
403 case GLib.IOStatus.EOF:
411 //print("RETURNING");
412 return false; // allow it to be called again..
420 args: ['ls', '/tmp'],
423 } catch (e) { print(JSON.stringify(e)); }
425 var secs = (new Date()).getSeconds()
429 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
432 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }