2 /// # valac --pkg gio-2.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) => { ... });
22 public errordomain SpawnError {
31 * @param cwd {String} working directory. (defaults to home directory)
32 * @param args {Array} arguments eg. [ 'ls', '-l' ]
35 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
36 * @arg is_async {Boolean} (optional)return instantly, or wait for exit. (default no)
37 * @arg trhow_exceptions {Boolean} throw exception on failure (default no)
43 public class Spawn : Object
46 * @signal input called at start to send input when process starts?
47 * @return the string or null
49 public signal string? input();
51 * @signal output_line called when a line is recieved from the process.
54 public signal void output_line(string str);
56 * @signal finish called when the process has completed.
57 * @param {int} result_id (the unix return)
58 * @param {string} str (the output string)
59 * @param {string} stderr (the stderr output)
61 public signal void finish(int res, string str, string stderr);
67 public bool is_async = true;
68 public bool throw_exceptions = false;
70 public Spawn(string cwd, string[] args) throws Error
81 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
82 if (this.args.length < 0) {
83 throw new SpawnError.NO_ARGS("No arguments");
90 MainLoop ctx = null; // the mainloop ctx.
93 * @property output {String} resulting output
97 * @property stderr {String} resulting output from stderr
101 * @property result {Number} execution result.
103 public int result= 0;
105 * @property pid {Number} pid of child process (of false if it's not running)
109 * @property in_ch {GLib.IOChannel} input io channel
111 IOChannel in_ch = null;
113 * @property out_ch {GLib.IOChannel} output io channel
115 IOChannel out_ch = null;
117 * @property err_ch {GLib.IOChannel} stderr io channel
119 IOChannel err_ch = null;
121 * @property err_src {int} the watch for errors
126 * @property err_src {int} the watch for output
133 * Run the configured command.
134 * result is applied to object properties (eg. '?' or 'stderr')
135 * @returns {Object} self.
137 public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
149 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
152 Process.spawn_async_with_pipes (
156 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
166 //print(JSON.stringify(gret));
168 GLib.debug("PID: %d" ,this.pid);
171 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
172 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
173 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
175 // make everything non-blocking!
179 // using NONBLOCKING only works if io_add_watch
180 //returns true/false in right conditions
181 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
182 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
183 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
188 ChildWatch.add (this.pid, (w_pid, result) => {
190 this.result = result;
191 GLib.debug("child_watch_add : result:%d ", result);
194 this.read(this.out_ch);
195 this.read(this.err_ch);
198 Process.close_pid(this.pid);
200 if (this.ctx != null) {
205 //print("DONE TIDYUP");
207 this.finish(this.result, this.output, this.stderr);
216 // add handlers for output and stderr.
218 this.out_src = (int) this.out_ch.add_watch (
219 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
220 (channel, condition) => {
221 return this.read(this.out_ch);
224 this.err_src = (int) this.err_ch.add_watch (
225 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
226 (channel, condition) => {
227 return this.read(this.err_ch);
234 // child can exit before we get this far..
235 var input = this.input();
240 // this probably needs to be a bit smarter...
241 //but... let's close input now..
242 this.in_ch.shutdown(true);
256 // async - if running - return..
257 if (this.is_async && this.pid > -1) {
261 // start mainloop if not async..
264 GLib.debug("starting main loop");
265 //if (this.cfg.debug) {
268 this.ctx = new MainLoop ();
269 this.ctx.run(); // wait fore exit?
271 GLib.debug("main_loop done!");
273 this.tidyup(); // tidyup get's called in main loop.
276 if (this.throw_exceptions && this.result != 0) {
278 throw new SpawnError.EXECUTE_ERROR(this.stderr);
279 //this.toString = function() { return this.stderr; };
280 ///throw new Exception this; // we throw self...
283 // finally throw, or return self..
291 private void tidyup()
294 Process.close_pid(this.pid); // hopefully kills it..
298 if (this.in_ch != null) this.in_ch.shutdown(true);
299 if (this.out_ch != null) this.out_ch.shutdown(true);
300 if (this.err_ch != null) this.err_ch.shutdown(true);
302 // error shutting donw.
304 // blank out channels
308 // rmeove listeners !! important otherwise we kill the CPU
309 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
310 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
318 * write to stdin of process
319 * @arg str {String} string to write to stdin of process
320 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
322 private int write(string str) throws Error // write a line to
324 if (this.in_ch == null) {
325 return 0; // input is closed
327 //print("write: " + str);
328 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
331 var res = this.in_ch.write_chars(str.to_utf8(), out written);
333 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
335 if (res != GLib.IOStatus.NORMAL) {
336 throw new SpawnError.WRITE_ERROR("Write failed");
346 * read from pipe and call appropriate listerner and add to output or stderr string.
347 * @arg giochannel to read from.
350 private bool read(IOChannel ch)
352 string prop = (ch == this.out_ch) ? "output" : "stderr";
353 // print("prop: " + prop);
356 //print(JSON.stringify(ch, null,4));
363 status = ch.read_line( out buffer, out len, out term_pos );
370 // print('status: ' +JSON.stringify(status));
371 // print(JSON.stringify(x));
373 case GLib.IOStatus.NORMAL:
377 //if (this.listeners[prop]) {
378 // this.listeners[prop].call(this, x.str_return);
380 if (ch == this.out_ch) {
381 this.output += buffer;
382 this.output_line( buffer);
385 this.stderr += buffer;
387 //_this[prop] += x.str_return;
388 //if (this.cfg.debug) {
389 GLib.debug("%s : %s", prop , buffer);
393 //if ( Gtk.events_pending()) {
394 // Gtk.main_iteration();
399 //this.ctx.iteration(true);
401 case GLib.IOStatus.AGAIN:
402 //print("Should be called again.. waiting for more data..");
405 case GLib.IOStatus.ERROR:
406 case GLib.IOStatus.EOF:
414 //print("RETURNING");
415 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.finish.connect((res, str, stderr) => {
436 ctx.run(); // wait for exit?