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
55 public signal void output_line(string str);
56 public signal void finish(int res, string str, string stderr);
62 public Spawn(string cwd, string[] args) throws Error
73 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
74 if (this.args.length < 0) {
75 throw new SpawnError.NO_ARGS("No arguments");
82 MainLoop ctx = null; // the mainloop ctx.
85 * @property output {String} resulting output
89 * @property stderr {String} resulting output from stderr
93 * @property result {Number} execution result.
97 * @property pid {Number} pid of child process (of false if it's not running)
101 * @property in_ch {GLib.IOChannel} input io channel
103 IOChannel in_ch = null;
105 * @property out_ch {GLib.IOChannel} output io channel
107 IOChannel out_ch = null;
109 * @property err_ch {GLib.IOChannel} stderr io channel
111 IOChannel err_ch = null;
113 * @property err_src {int} the watch for errors
118 * @property err_src {int} the watch for output
125 * Run the configured command.
126 * result is applied to object properties (eg. '?' or 'stderr')
127 * @returns {Object} self.
129 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
141 if (this.cfg.debug) {
142 stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
145 Process.spawn_async_with_pipes (
149 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
159 //print(JSON.stringify(gret));
161 if (this.cfg.debug) {
163 stdout.printf("PID: %d" ,this.pid);
166 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
167 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
168 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
170 // make everything non-blocking!
174 // using NONBLOCKING only works if io_add_watch
175 //returns true/false in right conditions
176 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
177 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
178 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
183 ChildWatch.add (this.pid, (w_pid, result) => {
185 this.result = result;
186 if (this.cfg.debug) {
187 stdout.printf("child_watch_add : result:%d ", result);
190 this.read(this.out_ch);
191 this.read(this.err_ch);
194 Process.close_pid(this.pid);
196 if (this.ctx != null) {
201 //print("DONE TIDYUP");
202 if (this.cfg.finish != null) {
203 this.cfg.finish(this.result);
212 // add handlers for output and stderr.
214 this.out_src = (int) this.out_ch.add_watch (
215 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
216 (channel, condition) => {
217 return this.read(this.out_ch);
220 this.err_src = (int) this.err_ch.add_watch (
221 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
222 (channel, condition) => {
223 return this.read(this.err_ch);
230 // child can exit before we get this far..
231 if (this.cfg.input != null) {
232 if (this.cfg.debug) print("Trying to call listeners");
234 this.write(this.cfg.input());
235 // this probably needs to be a bit smarter...
236 //but... let's close input now..
237 this.in_ch.shutdown(true);
251 // async - if running - return..
252 if (this.cfg.async && this.pid > -1) {
256 // start mainloop if not async..
259 print("starting main loop");
260 //if (this.cfg.debug) {
263 this.ctx = new MainLoop ();
264 this.ctx.run(); // wait fore exit?
266 print("main_loop done!");
268 this.tidyup(); // tidyup get's called in main loop.
271 if (this.cfg.exceptions && this.result != 0) {
273 throw new SpawnError.EXECUTE_ERROR(this.stderr);
274 //this.toString = function() { return this.stderr; };
275 ///throw new Exception this; // we throw self...
278 // finally throw, or return self..
286 private void tidyup()
289 Process.close_pid(this.pid); // hopefully kills it..
293 if (this.in_ch != null) this.in_ch.shutdown(true);
294 if (this.out_ch != null) this.out_ch.shutdown(true);
295 if (this.err_ch != null) this.err_ch.shutdown(true);
297 // error shutting donw.
299 // blank out channels
303 // rmeove listeners !! important otherwise we kill the CPU
304 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
305 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
313 * write to stdin of process
314 * @arg str {String} string to write to stdin of process
315 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
317 private int write(string str) throws Error // write a line to
319 if (this.in_ch == null) {
320 return 0; // input is closed
322 //print("write: " + str);
323 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
326 var res = this.in_ch.write_chars(str.to_utf8(), out written);
328 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
330 if (res != GLib.IOStatus.NORMAL) {
331 throw new SpawnError.WRITE_ERROR("Write failed");
341 * read from pipe and call appropriate listerner and add to output or stderr string.
342 * @arg giochannel to read from.
345 private bool read(IOChannel ch)
347 string prop = (ch == this.out_ch) ? "output" : "stderr";
348 // print("prop: " + prop);
351 //print(JSON.stringify(ch, null,4));
358 status = ch.read_line( out buffer, out len, out term_pos );
365 // print('status: ' +JSON.stringify(status));
366 // print(JSON.stringify(x));
368 case GLib.IOStatus.NORMAL:
372 //if (this.listeners[prop]) {
373 // this.listeners[prop].call(this, x.str_return);
375 if (ch == this.out_ch) {
376 this.output += buffer;
377 if (this.cfg.output != null) {
378 this.cfg.output( buffer);
381 this.stderr += buffer;
383 //_this[prop] += x.str_return;
384 //if (this.cfg.debug) {
385 stdout.printf("%s : %s", prop , buffer);
387 if (this.cfg.async) {
389 if ( Gtk.events_pending()) {
390 Gtk.main_iteration();
395 //this.ctx.iteration(true);
397 case GLib.IOStatus.AGAIN:
398 //print("Should be called again.. waiting for more data..");
401 case GLib.IOStatus.ERROR:
402 case GLib.IOStatus.EOF:
410 //print("RETURNING");
411 return false; // allow it to be called again..
419 args: ['ls', '/tmp'],
422 } catch (e) { print(JSON.stringify(e)); }
424 var secs = (new Date()).getSeconds()
428 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
431 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }