2 /// # valac --pkg gio-2.0 --pkg posix Spawn.vala -o /tmp/Spawn
10 * x = new Spawn( "/tmp", {"ls", "-l" })
12 * // these are optionall..
13 * x.env = ..... (if you need to set one...
14 * x.output_line.connect((string str) => {
15 * if ( Gtk.events_pending()) { Gtk.main_iteration(); }
17 * x.input_line.connect(() => { return string });
19 * x.run((int res, string output, string stderr) => { ... });
27 public errordomain SpawnError {
36 * @param cwd {String} working directory. (defaults to home directory)
37 * @param args {Array} arguments eg. [ 'ls', '-l' ]
40 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
41 * @arg is_async {Boolean} (optional)return instantly, or wait for exit. (default no)
42 * @arg trhow_exceptions {Boolean} throw exception on failure (default no)
48 public delegate void SpawnFinish (int res, string str, string stderr);
50 public class Spawn : Object
53 * @signal input called at start to send input when process starts?
54 * @return the string or null
56 public signal string? input();
58 * @signal output_line called when a line is recieved from the process.
59 * Note you may want to connect this and run
60 * if ( Gtk.events_pending()) { Gtk.main_iteration(); }
64 public signal void output_line(string str);
70 public bool is_async = true;
71 public bool throw_exceptions = false;
73 public Spawn(string cwd, string[] args) throws Error
84 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
85 if (this.args.length < 0) {
86 throw new SpawnError.NO_ARGS("No arguments");
93 MainLoop ctx = null; // the mainloop ctx.
96 * @property output {String} resulting output
100 * @property stderr {String} resulting output from stderr
102 public string stderr;
104 * @property result {Number} execution result.
106 public int result= 0;
108 * @property pid {Number} pid of child process (of false if it's not running)
112 * @property in_ch {GLib.IOChannel} input io channel
114 IOChannel in_ch = null;
116 * @property out_ch {GLib.IOChannel} output io channel
118 IOChannel out_ch = null;
120 * @property err_ch {GLib.IOChannel} stderr io channel
122 IOChannel err_ch = null;
124 * @property err_src {int} the watch for errors
129 * @property err_src {int} the watch for output
136 * Run the configured command.
137 * result is applied to object properties (eg. '?' or 'stderr')
138 * @returns {Object} self.
140 public void run(SpawnFinish finish) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
152 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
155 Process.spawn_async_with_pipes (
159 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
169 //print(JSON.stringify(gret));
171 GLib.debug("PID: %d" ,this.pid);
174 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
175 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
176 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
178 // make everything non-blocking!
182 // using NONBLOCKING only works if io_add_watch
183 //returns true/false in right conditions
184 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
185 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
186 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
191 ChildWatch.add (this.pid, (w_pid, result) => {
193 this.result = result;
194 GLib.debug("child_watch_add : result:%d ", result);
197 this.read(this.out_ch);
198 this.read(this.err_ch);
201 Process.close_pid(this.pid);
203 if (this.ctx != null) {
208 //print("DONE TIDYUP");
210 finish(this.result, this.output, this.stderr);
219 // add handlers for output and stderr.
221 this.out_src = (int) this.out_ch.add_watch (
222 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
223 (channel, condition) => {
224 return this.read(this.out_ch);
227 this.err_src = (int) this.err_ch.add_watch (
228 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
229 (channel, condition) => {
230 return this.read(this.err_ch);
237 // child can exit before we get this far..
238 var input = this.input();
243 // this probably needs to be a bit smarter...
244 //but... let's close input now..
245 this.in_ch.shutdown(true);
259 // async - if running - return..
260 if (this.is_async && this.pid > -1) {
264 // start mainloop if not async..
267 GLib.debug("starting main loop");
268 //if (this.cfg.debug) {
271 this.ctx = new MainLoop ();
272 this.ctx.run(); // wait fore exit?
274 GLib.debug("main_loop done!");
276 this.tidyup(); // tidyup get's called in main loop.
279 if (this.throw_exceptions && this.result != 0) {
281 throw new SpawnError.EXECUTE_ERROR(this.stderr);
282 //this.toString = function() { return this.stderr; };
283 ///throw new Exception this; // we throw self...
286 // finally throw, or return self..
294 private void tidyup()
297 Process.close_pid(this.pid); // hopefully kills it..
301 if (this.in_ch != null) this.in_ch.shutdown(true);
302 if (this.out_ch != null) this.out_ch.shutdown(true);
303 if (this.err_ch != null) this.err_ch.shutdown(true);
305 // error shutting donw.
307 // blank out channels
311 // rmeove listeners !! important otherwise we kill the CPU
312 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
313 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
321 * write to stdin of process
322 * @arg str {String} string to write to stdin of process
323 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
325 private int write(string str) throws Error // write a line to
327 if (this.in_ch == null) {
328 return 0; // input is closed
330 //print("write: " + str);
331 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
334 var res = this.in_ch.write_chars(str.to_utf8(), out written);
336 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
338 if (res != GLib.IOStatus.NORMAL) {
339 throw new SpawnError.WRITE_ERROR("Write failed");
349 * read from pipe and call appropriate listerner and add to output or stderr string.
350 * @arg giochannel to read from.
353 private bool read(IOChannel ch)
355 string prop = (ch == this.out_ch) ? "output" : "stderr";
356 // print("prop: " + prop);
359 //print(JSON.stringify(ch, null,4));
366 status = ch.read_line( out buffer, out len, out term_pos );
373 // print('status: ' +JSON.stringify(status));
374 // print(JSON.stringify(x));
376 case GLib.IOStatus.NORMAL:
380 //if (this.listeners[prop]) {
381 // this.listeners[prop].call(this, x.str_return);
383 if (ch == this.out_ch) {
384 this.output += buffer;
385 this.output_line( buffer);
388 this.stderr += buffer;
390 //_this[prop] += x.str_return;
391 //if (this.cfg.debug) {
392 GLib.debug("%s : %s", prop , buffer);
396 //if ( Gtk.events_pending()) {
397 // Gtk.main_iteration();
402 //this.ctx.iteration(true);
404 case GLib.IOStatus.AGAIN:
405 //print("Should be called again.. waiting for more data..");
408 case GLib.IOStatus.ERROR:
409 case GLib.IOStatus.EOF:
417 //print("RETURNING");
418 return false; // allow it to be called again..
424 int main (string[] args) {
425 GLib.Log.set_handler(null,
426 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING,
428 print("%s: %s\n", dom, msg);
431 var ctx = new GLib.MainLoop ();
432 var a = new Spawn("", { "ls" , "-l"});
433 a.run((res, str, stderr) => {
439 ctx.run(); // wait for exit?