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;
75 public Spawn(string cwd, string[] args) throws Error
86 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
87 if (this.args.length < 0) {
88 throw new SpawnError.NO_ARGS("No arguments");
95 MainLoop ctx = null; // the mainloop ctx.
98 * @property output {String} resulting output
100 public string output;
102 * @property stderr {String} resulting output from stderr
104 public string stderr;
106 * @property result {Number} execution result.
108 public int result= 0;
110 * @property pid {Number} pid of child process (of false if it's not running)
114 * @property in_ch {GLib.IOChannel} input io channel
116 IOChannel in_ch = null;
118 * @property out_ch {GLib.IOChannel} output io channel
120 IOChannel out_ch = null;
122 * @property err_ch {GLib.IOChannel} stderr io channel
124 IOChannel err_ch = null;
126 * @property err_src {int} the watch for errors
131 * @property err_src {int} the watch for output
138 * Run the configured command.
139 * result is applied to object properties (eg. '?' or 'stderr')
140 * @returns {Object} self.
142 public void run( ) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
154 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
157 Process.spawn_async_with_pipes (
160 this.env.length > 0 ? this.env : null,
161 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
171 //print(JSON.stringify(gret));
173 GLib.debug("PID: %d" ,this.pid);
176 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
177 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
178 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
180 // make everything non-blocking!
184 // using NONBLOCKING only works if io_add_watch
185 //returns true/false in right conditions
186 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
187 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
188 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
193 ChildWatch.add (this.pid, (w_pid, result) => {
195 this.result = result;
196 GLib.debug("child_watch_add : result:%d ", result);
199 this.read(this.out_ch);
200 this.read(this.err_ch);
203 Process.close_pid(this.pid);
205 if (this.ctx != null) {
210 //print("DONE TIDYUP");
212 this.complete(this.result, this.output, this.stderr);
221 // add handlers for output and stderr.
223 this.out_src = (int) this.out_ch.add_watch (
224 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
225 (channel, condition) => {
226 return this.read(this.out_ch);
229 this.err_src = (int) this.err_ch.add_watch (
230 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
231 (channel, condition) => {
232 return this.read(this.err_ch);
239 // child can exit before we get this far..
240 var input = this.input();
245 // this probably needs to be a bit smarter...
246 //but... let's close input now..
247 this.in_ch.shutdown(true);
261 // async - if running - return..
262 if (this.is_async && this.pid > -1) {
266 // start mainloop if not async..
269 GLib.debug("starting main loop");
270 //if (this.cfg.debug) {
273 this.ctx = new MainLoop ();
274 this.ctx.run(); // wait fore exit?
276 GLib.debug("main_loop done!");
278 this.tidyup(); // tidyup get's called in main loop.
281 if (this.throw_exceptions && this.result != 0) {
283 throw new SpawnError.EXECUTE_ERROR(this.stderr);
284 //this.toString = function() { return this.stderr; };
285 ///throw new Exception this; // we throw self...
288 // finally throw, or return self..
296 private void tidyup()
299 Process.close_pid(this.pid); // hopefully kills it..
303 if (this.in_ch != null) this.in_ch.shutdown(true);
304 if (this.out_ch != null) this.out_ch.shutdown(true);
305 if (this.err_ch != null) this.err_ch.shutdown(true);
307 // error shutting donw.
309 // blank out channels
313 // rmeove listeners !! important otherwise we kill the CPU
314 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
315 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
323 * write to stdin of process
324 * @arg str {String} string to write to stdin of process
325 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
327 private int write(string str) throws Error // write a line to
329 if (this.in_ch == null) {
330 return 0; // input is closed
332 //print("write: " + str);
333 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
336 var res = this.in_ch.write_chars(str.to_utf8(), out written);
338 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
340 if (res != GLib.IOStatus.NORMAL) {
341 throw new SpawnError.WRITE_ERROR("Write failed");
351 * read from pipe and call appropriate listerner and add to output or stderr string.
352 * @arg giochannel to read from.
355 private bool read(IOChannel ch)
357 string prop = (ch == this.out_ch) ? "output" : "stderr";
358 // print("prop: " + prop);
361 //print(JSON.stringify(ch, null,4));
368 status = ch.read_line( out buffer, out len, out term_pos );
375 // print('status: ' +JSON.stringify(status));
376 // print(JSON.stringify(x));
378 case GLib.IOStatus.NORMAL:
382 //if (this.listeners[prop]) {
383 // this.listeners[prop].call(this, x.str_return);
385 if (ch == this.out_ch) {
386 this.output += buffer;
387 this.output_line( buffer);
390 this.stderr += buffer;
392 //_this[prop] += x.str_return;
393 //if (this.cfg.debug) {
394 //GLib.debug("%s : %s", prop , buffer);
398 //if ( Gtk.events_pending()) {
399 // Gtk.main_iteration();
404 //this.ctx.iteration(true);
406 case GLib.IOStatus.AGAIN:
407 //print("Should be called again.. waiting for more data..");
410 case GLib.IOStatus.ERROR:
411 case GLib.IOStatus.EOF:
419 //print("RETURNING");
420 return false; // allow it to be called again..
426 int main (string[] args) {
427 GLib.Log.set_handler(null,
428 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING,
430 print("%s: %s\n", dom, msg);
433 var ctx = new GLib.MainLoop ();
434 var a = new Spawn("", { "ls" , "-l"});
435 a.run((res, str, stderr) => {
441 ctx.run(); // wait for exit?