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;
62 public bool is_async = true;
63 public bool throw_exceptions = false;
65 public Spawn(string cwd, string[] args) throws Error
76 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
77 if (this.args.length < 0) {
78 throw new SpawnError.NO_ARGS("No arguments");
85 MainLoop ctx = null; // the mainloop ctx.
88 * @property output {String} resulting output
92 * @property stderr {String} resulting output from stderr
96 * @property result {Number} execution result.
100 * @property pid {Number} pid of child process (of false if it's not running)
104 * @property in_ch {GLib.IOChannel} input io channel
106 IOChannel in_ch = null;
108 * @property out_ch {GLib.IOChannel} output io channel
110 IOChannel out_ch = null;
112 * @property err_ch {GLib.IOChannel} stderr io channel
114 IOChannel err_ch = null;
116 * @property err_src {int} the watch for errors
121 * @property err_src {int} the watch for output
128 * Run the configured command.
129 * result is applied to object properties (eg. '?' or 'stderr')
130 * @returns {Object} self.
132 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
144 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
147 Process.spawn_async_with_pipes (
151 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
161 //print(JSON.stringify(gret));
163 GLib.debug("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 GLib.debug("child_watch_add : result:%d ", result);
189 this.read(this.out_ch);
190 this.read(this.err_ch);
193 Process.close_pid(this.pid);
195 if (this.ctx != null) {
200 //print("DONE TIDYUP");
202 this.finish(this.result, this.output, this.stderr);
211 // add handlers for output and stderr.
213 this.out_src = (int) this.out_ch.add_watch (
214 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
215 (channel, condition) => {
216 return this.read(this.out_ch);
219 this.err_src = (int) this.err_ch.add_watch (
220 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
221 (channel, condition) => {
222 return this.read(this.err_ch);
229 // child can exit before we get this far..
230 var input = this.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.is_async && this.pid > -1) {
256 // start mainloop if not async..
259 GLib.debug("starting main loop");
260 //if (this.cfg.debug) {
263 this.ctx = new MainLoop ();
264 this.ctx.run(); // wait fore exit?
266 GLib.debug("main_loop done!");
268 this.tidyup(); // tidyup get's called in main loop.
271 if (this.throw_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 this.line_output( buffer);
380 this.stderr += buffer;
382 //_this[prop] += x.str_return;
383 //if (this.cfg.debug) {
384 GLib.debug("%s : %s", prop , buffer);
386 if (this.cfg.async) {
388 if ( Gtk.events_pending()) {
389 Gtk.main_iteration();
394 //this.ctx.iteration(true);
396 case GLib.IOStatus.AGAIN:
397 //print("Should be called again.. waiting for more data..");
400 case GLib.IOStatus.ERROR:
401 case GLib.IOStatus.EOF:
409 //print("RETURNING");
410 return false; // allow it to be called again..