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)
47 public class Spawn : Object
50 * @signal input called at start to send input when process starts?
51 * @return the string or null
53 public signal string? input();
55 * @signal complete called at when the command has completed.
58 public signal void complete(int res, string str, string stderr);
60 * @signal output_line called when a line is recieved from the process.
61 * Note you may want to connect this and run
62 * if ( Gtk.events_pending()) { Gtk.main_iteration(); }
66 public signal void output_line(string str);
72 public bool is_async = true;
73 public bool throw_exceptions = false;
74 public bool detach = false;
76 public Spawn(string cwd, string[] args) throws Error
87 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
88 if (this.args.length < 0) {
89 throw new SpawnError.NO_ARGS("No arguments");
96 MainLoop ctx = null; // the mainloop ctx.
99 * @property output {String} resulting output
101 public string output;
103 * @property stderr {String} resulting output from stderr
105 public string stderr;
107 * @property result {Number} execution result.
109 public int result= 0;
111 * @property pid {Number} pid of child process (of false if it's not running)
119 * @property in_ch {GLib.IOChannel} input io channel
121 IOChannel in_ch = null;
123 * @property out_ch {GLib.IOChannel} output io channel
125 IOChannel out_ch = null;
127 * @property err_ch {GLib.IOChannel} stderr io channel
129 IOChannel err_ch = null;
131 * @property err_src {int} the watch for errors
136 * @property err_src {int} the watch for output
143 * Run the configured command.
144 * result is applied to object properties (eg. '?' or 'stderr')
145 * @returns {Object} self.
147 public void run( ) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
159 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
163 //Process.spawn_async_with_pipes (
164 Process.spawn_async (
167 this.env.length > 0 ? this.env : null,
168 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
174 ChildWatch.add (this.pid, (pid, status) => {
176 Process.close_pid (pid);
185 Process.spawn_async_with_pipes (
188 this.env.length > 0 ? this.env : null,
189 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
199 //print(JSON.stringify(gret));
201 GLib.debug("PID: %d" ,this.pid);
204 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
205 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
206 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
208 // make everything non-blocking!
212 // using NONBLOCKING only works if io_add_watch
213 //returns true/false in right conditions
214 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
215 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
216 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
221 ChildWatch.add (this.pid, (w_pid, result) => {
223 this.result = result;
224 GLib.debug("child_watch_add : result:%d ", result);
227 this.read(this.out_ch);
228 this.read(this.err_ch);
231 Process.close_pid(this.pid);
233 if (this.ctx != null) {
238 GLib.debug("DONE TIDYUP - calling complete");
240 this.complete(this.result, this.output, this.stderr);
249 // add handlers for output and stderr.
251 this.out_src = (int) this.out_ch.add_watch (
252 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
253 (channel, condition) => {
254 return this.out_ch == null ? true : this.read(this.out_ch);
257 this.err_src = (int) this.err_ch.add_watch (
258 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
259 (channel, condition) => {
260 return this.err_ch == null ? true : this.read(this.err_ch);
267 // child can exit before we get this far..
268 var input = this.input();
273 // this probably needs to be a bit smarter...
274 //but... let's close input now..
275 this.in_ch.shutdown(true);
289 // async - if running - return..
290 if (this.is_async && this.pid > -1) {
294 // start mainloop if not async..
297 GLib.debug("starting main loop");
298 //if (this.cfg.debug) {
301 this.ctx = new MainLoop ();
302 this.ctx.run(); // wait fore exit?
304 GLib.debug("main_loop done!");
306 this.tidyup(); // tidyup get's called in main loop.
309 if (this.throw_exceptions && this.result != 0) {
311 throw new SpawnError.EXECUTE_ERROR(this.stderr);
312 //this.toString = function() { return this.stderr; };
313 ///throw new Exception this; // we throw self...
316 // finally throw, or return self..
322 public async int run_async()
324 GLib.MainLoop loop = new GLib.MainLoop ();
325 this.complete.connect( (res, str, stderr) => {
341 public void tidyup() // or kill
344 Process.close_pid(this.pid); // hopefully kills it..
348 if (this.in_ch != null) this.in_ch.shutdown(true);
349 if (this.out_ch != null) this.out_ch.shutdown(true);
350 if (this.err_ch != null) this.err_ch.shutdown(true);
352 // error shutting donw.
354 // blank out channels
358 // rmeove listeners !! important otherwise we kill the CPU
359 if (this.err_src > -1 ) GLib.Source.remove(this.err_src);
360 if (this.out_src > -1 ) GLib.Source.remove(this.out_src);
368 * write to stdin of process
369 * @arg str {String} string to write to stdin of process
370 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
372 private int write(string str) throws Error // write a line to
374 if (this.in_ch == null) {
375 return 0; // input is closed
377 //print("write: " + str);
378 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
381 var res = this.in_ch.write_chars(str.to_utf8(), out written);
383 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
385 if (res != GLib.IOStatus.NORMAL) {
386 throw new SpawnError.WRITE_ERROR("Write failed");
396 * read from pipe and call appropriate listerner and add to output or stderr string.
397 * @arg giochannel to read from.
400 private bool read(IOChannel ch)
402 // string prop = (ch == this.out_ch) ? "output" : "stderr";
403 // print("prop: " + prop);
406 //print(JSON.stringify(ch, null,4));
413 status = ch.read_line( out buffer, out len, out term_pos );
420 // print('status: ' +JSON.stringify(status));
421 // print(JSON.stringify(x));
423 case GLib.IOStatus.NORMAL:
427 //if (this.listeners[prop]) {
428 // this.listeners[prop].call(this, x.str_return);
430 if (ch == this.out_ch) {
431 this.output += buffer;
432 this.output_line( buffer);
435 this.stderr += buffer;
436 this.output_line( buffer);
438 //_this[prop] += x.str_return;
439 //if (this.cfg.debug) {
440 //GLib.debug("%s : %s", prop , buffer);
444 //if ( Gtk.events_pending()) {
445 // Gtk.main_iteration();
450 //this.ctx.iteration(true);
452 case GLib.IOStatus.AGAIN:
453 //print("Should be called again.. waiting for more data..");
456 case GLib.IOStatus.ERROR:
457 case GLib.IOStatus.EOF:
465 //print("RETURNING");
466 return false; // allow it to be called again..
468 public bool isZombie()
470 if (!GLib.FileUtils.test("/proc/%d".printf(this.pid), FileTest.EXISTS)) {
476 if (!GLib.FileUtils.get_contents("/proc/%d/stat".printf(this.pid), out f, out sz)) {
479 } catch(GLib.Error e) {
482 var bits = f.split(" ");
483 if (bits.length > 3 && bits[2] == "Z") {
484 GLib.debug("Process pid:%d is a zombie - trying waitpid", this.pid);
486 Posix.waitpid(this.pid, out status, 0);
487 GLib.debug("Process pid:%d is a zombie - done waitpid", this.pid);
500 int main (string[] args) {
501 GLib.Log.set_handler(null,
502 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING,
504 print("%s: %s\n", dom, msg);
507 var ctx = new GLib.MainLoop ();
508 var a = new Spawn("", { "ls" , "-l"});
509 a.run((res, str, stderr) => {
515 ctx.run(); // wait for exit?