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
142 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
145 Process.spawn_async_with_pipes (
149 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
159 //print(JSON.stringify(gret));
161 GLib.debug("PID: %d" ,this.pid);
164 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
165 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
166 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
168 // make everything non-blocking!
172 // using NONBLOCKING only works if io_add_watch
173 //returns true/false in right conditions
174 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
175 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
176 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
181 ChildWatch.add (this.pid, (w_pid, result) => {
183 this.result = result;
184 GLib.debug("child_watch_add : result:%d ", result);
187 this.read(this.out_ch);
188 this.read(this.err_ch);
191 Process.close_pid(this.pid);
193 if (this.ctx != null) {
198 //print("DONE TIDYUP");
200 this.finish(this.result, this.output, this.stderr);
209 // add handlers for output and stderr.
211 this.out_src = (int) this.out_ch.add_watch (
212 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
213 (channel, condition) => {
214 return this.read(this.out_ch);
217 this.err_src = (int) this.err_ch.add_watch (
218 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
219 (channel, condition) => {
220 return this.read(this.err_ch);
227 // child can exit before we get this far..
228 var input = this.input();
233 // this probably needs to be a bit smarter...
234 //but... let's close input now..
235 this.in_ch.shutdown(true);
249 // async - if running - return..
250 if (this.cfg.async && this.pid > -1) {
254 // start mainloop if not async..
257 print("starting main loop");
258 //if (this.cfg.debug) {
261 this.ctx = new MainLoop ();
262 this.ctx.run(); // wait fore exit?
264 print("main_loop done!");
266 this.tidyup(); // tidyup get's called in main loop.
269 if (this.cfg.exceptions && this.result != 0) {
271 throw new SpawnError.EXECUTE_ERROR(this.stderr);
272 //this.toString = function() { return this.stderr; };
273 ///throw new Exception this; // we throw self...
276 // finally throw, or return self..
284 private void tidyup()
287 Process.close_pid(this.pid); // hopefully kills it..
291 if (this.in_ch != null) this.in_ch.shutdown(true);
292 if (this.out_ch != null) this.out_ch.shutdown(true);
293 if (this.err_ch != null) this.err_ch.shutdown(true);
295 // error shutting donw.
297 // blank out channels
301 // rmeove listeners !! important otherwise we kill the CPU
302 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
303 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
311 * write to stdin of process
312 * @arg str {String} string to write to stdin of process
313 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
315 private int write(string str) throws Error // write a line to
317 if (this.in_ch == null) {
318 return 0; // input is closed
320 //print("write: " + str);
321 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
324 var res = this.in_ch.write_chars(str.to_utf8(), out written);
326 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
328 if (res != GLib.IOStatus.NORMAL) {
329 throw new SpawnError.WRITE_ERROR("Write failed");
339 * read from pipe and call appropriate listerner and add to output or stderr string.
340 * @arg giochannel to read from.
343 private bool read(IOChannel ch)
345 string prop = (ch == this.out_ch) ? "output" : "stderr";
346 // print("prop: " + prop);
349 //print(JSON.stringify(ch, null,4));
356 status = ch.read_line( out buffer, out len, out term_pos );
363 // print('status: ' +JSON.stringify(status));
364 // print(JSON.stringify(x));
366 case GLib.IOStatus.NORMAL:
370 //if (this.listeners[prop]) {
371 // this.listeners[prop].call(this, x.str_return);
373 if (ch == this.out_ch) {
374 this.output += buffer;
375 if (this.cfg.output != null) {
376 this.cfg.output( buffer);
379 this.stderr += buffer;
381 //_this[prop] += x.str_return;
382 //if (this.cfg.debug) {
383 stdout.printf("%s : %s", prop , buffer);
385 if (this.cfg.async) {
387 if ( Gtk.events_pending()) {
388 Gtk.main_iteration();
393 //this.ctx.iteration(true);
395 case GLib.IOStatus.AGAIN:
396 //print("Should be called again.. waiting for more data..");
399 case GLib.IOStatus.ERROR:
400 case GLib.IOStatus.EOF:
408 //print("RETURNING");
409 return false; // allow it to be called again..
417 args: ['ls', '/tmp'],
420 } catch (e) { print(JSON.stringify(e)); }
422 var secs = (new Date()).getSeconds()
426 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
429 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }