2 /// # valac --pkg gio-2.0 --pkg posix Spawn.vala -o /tmp/Spawn
10 * x = new Spawn( working dir, args)
12 * // these are optionall..
13 * x.env = ..... (if you need to set one...
14 * x.output_line.connect((string str) => { ... });
15 * x.input_line.connect(() => { return string });
17 * x.run((int res, string output, string stderr) => { ... });
25 public errordomain SpawnError {
34 * @param cwd {String} working directory. (defaults to home directory)
35 * @param args {Array} arguments eg. [ 'ls', '-l' ]
38 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
39 * @arg is_async {Boolean} (optional)return instantly, or wait for exit. (default no)
40 * @arg trhow_exceptions {Boolean} throw exception on failure (default no)
46 delegate void SpawnFinish (int res, string str, string stderr);
48 public class Spawn : Object
51 * @signal input called at start to send input when process starts?
52 * @return the string or null
54 public signal string? input();
56 * @signal output_line called when a line is recieved from the process.
57 * Note you may want to connect this and run
58 * if ( Gtk.events_pending()) { Gtk.main_iteration(); }
62 public signal void output_line(string str);
68 public bool is_async = true;
69 public bool throw_exceptions = false;
71 public Spawn(string cwd, string[] args) throws Error
82 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
83 if (this.args.length < 0) {
84 throw new SpawnError.NO_ARGS("No arguments");
91 MainLoop ctx = null; // the mainloop ctx.
94 * @property output {String} resulting output
98 * @property stderr {String} resulting output from stderr
100 public string stderr;
102 * @property result {Number} execution result.
104 public int result= 0;
106 * @property pid {Number} pid of child process (of false if it's not running)
110 * @property in_ch {GLib.IOChannel} input io channel
112 IOChannel in_ch = null;
114 * @property out_ch {GLib.IOChannel} output io channel
116 IOChannel out_ch = null;
118 * @property err_ch {GLib.IOChannel} stderr io channel
120 IOChannel err_ch = null;
122 * @property err_src {int} the watch for errors
127 * @property err_src {int} the watch for output
134 * Run the configured command.
135 * result is applied to object properties (eg. '?' or 'stderr')
136 * @returns {Object} self.
138 public void run(SpawnFinish finish) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
150 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
153 Process.spawn_async_with_pipes (
157 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
167 //print(JSON.stringify(gret));
169 GLib.debug("PID: %d" ,this.pid);
172 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
173 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
174 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
176 // make everything non-blocking!
180 // using NONBLOCKING only works if io_add_watch
181 //returns true/false in right conditions
182 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
183 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
184 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
189 ChildWatch.add (this.pid, (w_pid, result) => {
191 this.result = result;
192 GLib.debug("child_watch_add : result:%d ", result);
195 this.read(this.out_ch);
196 this.read(this.err_ch);
199 Process.close_pid(this.pid);
201 if (this.ctx != null) {
206 //print("DONE TIDYUP");
208 finish(this.result, this.output, this.stderr);
217 // add handlers for output and stderr.
219 this.out_src = (int) this.out_ch.add_watch (
220 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
221 (channel, condition) => {
222 return this.read(this.out_ch);
225 this.err_src = (int) this.err_ch.add_watch (
226 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
227 (channel, condition) => {
228 return this.read(this.err_ch);
235 // child can exit before we get this far..
236 var input = this.input();
241 // this probably needs to be a bit smarter...
242 //but... let's close input now..
243 this.in_ch.shutdown(true);
257 // async - if running - return..
258 if (this.is_async && this.pid > -1) {
262 // start mainloop if not async..
265 GLib.debug("starting main loop");
266 //if (this.cfg.debug) {
269 this.ctx = new MainLoop ();
270 this.ctx.run(); // wait fore exit?
272 GLib.debug("main_loop done!");
274 this.tidyup(); // tidyup get's called in main loop.
277 if (this.throw_exceptions && this.result != 0) {
279 throw new SpawnError.EXECUTE_ERROR(this.stderr);
280 //this.toString = function() { return this.stderr; };
281 ///throw new Exception this; // we throw self...
284 // finally throw, or return self..
292 private void tidyup()
295 Process.close_pid(this.pid); // hopefully kills it..
299 if (this.in_ch != null) this.in_ch.shutdown(true);
300 if (this.out_ch != null) this.out_ch.shutdown(true);
301 if (this.err_ch != null) this.err_ch.shutdown(true);
303 // error shutting donw.
305 // blank out channels
309 // rmeove listeners !! important otherwise we kill the CPU
310 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
311 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
319 * write to stdin of process
320 * @arg str {String} string to write to stdin of process
321 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
323 private int write(string str) throws Error // write a line to
325 if (this.in_ch == null) {
326 return 0; // input is closed
328 //print("write: " + str);
329 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
332 var res = this.in_ch.write_chars(str.to_utf8(), out written);
334 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
336 if (res != GLib.IOStatus.NORMAL) {
337 throw new SpawnError.WRITE_ERROR("Write failed");
347 * read from pipe and call appropriate listerner and add to output or stderr string.
348 * @arg giochannel to read from.
351 private bool read(IOChannel ch)
353 string prop = (ch == this.out_ch) ? "output" : "stderr";
354 // print("prop: " + prop);
357 //print(JSON.stringify(ch, null,4));
364 status = ch.read_line( out buffer, out len, out term_pos );
371 // print('status: ' +JSON.stringify(status));
372 // print(JSON.stringify(x));
374 case GLib.IOStatus.NORMAL:
378 //if (this.listeners[prop]) {
379 // this.listeners[prop].call(this, x.str_return);
381 if (ch == this.out_ch) {
382 this.output += buffer;
383 this.output_line( buffer);
386 this.stderr += buffer;
388 //_this[prop] += x.str_return;
389 //if (this.cfg.debug) {
390 GLib.debug("%s : %s", prop , buffer);
394 //if ( Gtk.events_pending()) {
395 // Gtk.main_iteration();
400 //this.ctx.iteration(true);
402 case GLib.IOStatus.AGAIN:
403 //print("Should be called again.. waiting for more data..");
406 case GLib.IOStatus.ERROR:
407 case GLib.IOStatus.EOF:
415 //print("RETURNING");
416 return false; // allow it to be called again..
421 int main (string[] args) {
422 GLib.Log.set_handler(null,
423 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING,
425 print("%s: %s\n", dom, msg);
428 var ctx = new GLib.MainLoop ();
429 var a = new Spawn("", { "ls" , "-l"});
430 a.run((res, str, stderr) => {
436 ctx.run(); // wait for exit?