2 /// # valac --pkg gio-2.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) => { ... });
22 public errordomain SpawnError {
31 * @param cfg {SpawnConfig} settings - see properties.
33 * @arg cwd {String} working directory. (defaults to home directory)
34 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
35 * @arg listeners {Object} (optional) handlers for output, stderr, input
36 * stderr/output both receive output line as argument
37 * input should return any standard input
38 * finish recieves result as argument.
39 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
40 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
41 * @arg exceptions {Boolean} throw exception on failure (default no)
42 * @arg debug {Boolean} print out what's going on.. (default no)
47 public class Spawn : Object
49 public signal string? input();
50 public signal void output_line(string str);
51 public signal void finish(int res, string str, string stderr);
56 public bool debug = false;
57 public bool is_async = true;
58 public bool throw_exceptions = false;
60 public Spawn(string cwd, string[] args) throws Error
71 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
72 if (this.args.length < 0) {
73 throw new SpawnError.NO_ARGS("No arguments");
80 MainLoop ctx = null; // the mainloop ctx.
83 * @property output {String} resulting output
87 * @property stderr {String} resulting output from stderr
91 * @property result {Number} execution result.
95 * @property pid {Number} pid of child process (of false if it's not running)
99 * @property in_ch {GLib.IOChannel} input io channel
101 IOChannel in_ch = null;
103 * @property out_ch {GLib.IOChannel} output io channel
105 IOChannel out_ch = null;
107 * @property err_ch {GLib.IOChannel} stderr io channel
109 IOChannel err_ch = null;
111 * @property err_src {int} the watch for errors
116 * @property err_src {int} the watch for output
123 * Run the configured command.
124 * result is applied to object properties (eg. '?' or 'stderr')
125 * @returns {Object} self.
127 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
139 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
142 Process.spawn_async_with_pipes (
146 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
156 //print(JSON.stringify(gret));
158 GLib.debug("PID: %d" ,this.pid);
161 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
162 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
163 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
165 // make everything non-blocking!
169 // using NONBLOCKING only works if io_add_watch
170 //returns true/false in right conditions
171 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
172 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
173 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
178 ChildWatch.add (this.pid, (w_pid, result) => {
180 this.result = result;
181 GLib.debug("child_watch_add : result:%d ", result);
184 this.read(this.out_ch);
185 this.read(this.err_ch);
188 Process.close_pid(this.pid);
190 if (this.ctx != null) {
195 //print("DONE TIDYUP");
197 this.finish(this.result, this.output, this.stderr);
206 // add handlers for output and stderr.
208 this.out_src = (int) this.out_ch.add_watch (
209 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
210 (channel, condition) => {
211 return this.read(this.out_ch);
214 this.err_src = (int) this.err_ch.add_watch (
215 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
216 (channel, condition) => {
217 return this.read(this.err_ch);
224 // child can exit before we get this far..
225 var input = this.input();
230 // this probably needs to be a bit smarter...
231 //but... let's close input now..
232 this.in_ch.shutdown(true);
246 // async - if running - return..
247 if (this.is_async && this.pid > -1) {
251 // start mainloop if not async..
254 GLib.debug("starting main loop");
255 //if (this.cfg.debug) {
258 this.ctx = new MainLoop ();
259 this.ctx.run(); // wait fore exit?
261 GLib.debug("main_loop done!");
263 this.tidyup(); // tidyup get's called in main loop.
266 if (this.throw_exceptions && this.result != 0) {
268 throw new SpawnError.EXECUTE_ERROR(this.stderr);
269 //this.toString = function() { return this.stderr; };
270 ///throw new Exception this; // we throw self...
273 // finally throw, or return self..
281 private void tidyup()
284 Process.close_pid(this.pid); // hopefully kills it..
288 if (this.in_ch != null) this.in_ch.shutdown(true);
289 if (this.out_ch != null) this.out_ch.shutdown(true);
290 if (this.err_ch != null) this.err_ch.shutdown(true);
292 // error shutting donw.
294 // blank out channels
298 // rmeove listeners !! important otherwise we kill the CPU
299 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
300 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
308 * write to stdin of process
309 * @arg str {String} string to write to stdin of process
310 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
312 private int write(string str) throws Error // write a line to
314 if (this.in_ch == null) {
315 return 0; // input is closed
317 //print("write: " + str);
318 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
321 var res = this.in_ch.write_chars(str.to_utf8(), out written);
323 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
325 if (res != GLib.IOStatus.NORMAL) {
326 throw new SpawnError.WRITE_ERROR("Write failed");
336 * read from pipe and call appropriate listerner and add to output or stderr string.
337 * @arg giochannel to read from.
340 private bool read(IOChannel ch)
342 string prop = (ch == this.out_ch) ? "output" : "stderr";
343 // print("prop: " + prop);
346 //print(JSON.stringify(ch, null,4));
353 status = ch.read_line( out buffer, out len, out term_pos );
360 // print('status: ' +JSON.stringify(status));
361 // print(JSON.stringify(x));
363 case GLib.IOStatus.NORMAL:
367 //if (this.listeners[prop]) {
368 // this.listeners[prop].call(this, x.str_return);
370 if (ch == this.out_ch) {
371 this.output += buffer;
372 this.line_output( buffer);
375 this.stderr += buffer;
377 //_this[prop] += x.str_return;
378 //if (this.cfg.debug) {
379 GLib.debug("%s : %s", prop , buffer);
381 if (this.cfg.async) {
383 if ( Gtk.events_pending()) {
384 Gtk.main_iteration();
389 //this.ctx.iteration(true);
391 case GLib.IOStatus.AGAIN:
392 //print("Should be called again.. waiting for more data..");
395 case GLib.IOStatus.ERROR:
396 case GLib.IOStatus.EOF:
404 //print("RETURNING");
405 return false; // allow it to be called again..
411 int main (string[] args) {
412 var ctx = new GLib.MainLoop ();
413 var a = new Spawn("", { "ls" , "-l"});
414 a.finish.connect((res, str, stderr) => {
419 ctx.run(); // wait for exit?