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 void SpawnFinish (int res, string str, string stderr);
45 public class Spawn : Object
48 * @signal input called at start to send input when process starts?
49 * @return the string or null
51 public signal string? input();
53 * @signal output_line called when a line is recieved from the process.
54 * Note you may want to connect this and run
55 * if ( Gtk.events_pending()) { Gtk.main_iteration(); }
59 public signal void output_line(string str);
65 public bool is_async = true;
66 public bool throw_exceptions = false;
68 public Spawn(string cwd, string[] args) throws Error
79 this.cwd = this.cwd.length < 1 ? GLib.Environment.get_home_dir() : this.cwd;
80 if (this.args.length < 0) {
81 throw new SpawnError.NO_ARGS("No arguments");
88 MainLoop ctx = null; // the mainloop ctx.
91 * @property output {String} resulting output
95 * @property stderr {String} resulting output from stderr
99 * @property result {Number} execution result.
101 public int result= 0;
103 * @property pid {Number} pid of child process (of false if it's not running)
107 * @property in_ch {GLib.IOChannel} input io channel
109 IOChannel in_ch = null;
111 * @property out_ch {GLib.IOChannel} output io channel
113 IOChannel out_ch = null;
115 * @property err_ch {GLib.IOChannel} stderr io channel
117 IOChannel err_ch = null;
119 * @property err_src {int} the watch for errors
124 * @property err_src {int} the watch for output
131 * Run the configured command.
132 * result is applied to object properties (eg. '?' or 'stderr')
133 * @returns {Object} self.
135 public void run(SpawnFinish finish) throws SpawnError, GLib.SpawnError, GLib.IOChannelError
147 GLib.debug("cd %s; %s" , this.cwd , string.joinv(" ", this.args));
150 Process.spawn_async_with_pipes (
154 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
164 //print(JSON.stringify(gret));
166 GLib.debug("PID: %d" ,this.pid);
169 this.in_ch = new GLib.IOChannel.unix_new(standard_input);
170 this.out_ch = new GLib.IOChannel.unix_new(standard_output);
171 this.err_ch = new GLib.IOChannel.unix_new(standard_error);
173 // make everything non-blocking!
177 // using NONBLOCKING only works if io_add_watch
178 //returns true/false in right conditions
179 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
180 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
181 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
186 ChildWatch.add (this.pid, (w_pid, result) => {
188 this.result = result;
189 GLib.debug("child_watch_add : result:%d ", result);
192 this.read(this.out_ch);
193 this.read(this.err_ch);
196 Process.close_pid(this.pid);
198 if (this.ctx != null) {
203 //print("DONE TIDYUP");
205 this.finish(this.result, this.output, this.stderr);
214 // add handlers for output and stderr.
216 this.out_src = (int) this.out_ch.add_watch (
217 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
218 (channel, condition) => {
219 return this.read(this.out_ch);
222 this.err_src = (int) this.err_ch.add_watch (
223 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
224 (channel, condition) => {
225 return this.read(this.err_ch);
232 // child can exit before we get this far..
233 var input = this.input();
238 // this probably needs to be a bit smarter...
239 //but... let's close input now..
240 this.in_ch.shutdown(true);
254 // async - if running - return..
255 if (this.is_async && this.pid > -1) {
259 // start mainloop if not async..
262 GLib.debug("starting main loop");
263 //if (this.cfg.debug) {
266 this.ctx = new MainLoop ();
267 this.ctx.run(); // wait fore exit?
269 GLib.debug("main_loop done!");
271 this.tidyup(); // tidyup get's called in main loop.
274 if (this.throw_exceptions && this.result != 0) {
276 throw new SpawnError.EXECUTE_ERROR(this.stderr);
277 //this.toString = function() { return this.stderr; };
278 ///throw new Exception this; // we throw self...
281 // finally throw, or return self..
289 private void tidyup()
292 Process.close_pid(this.pid); // hopefully kills it..
296 if (this.in_ch != null) this.in_ch.shutdown(true);
297 if (this.out_ch != null) this.out_ch.shutdown(true);
298 if (this.err_ch != null) this.err_ch.shutdown(true);
300 // error shutting donw.
302 // blank out channels
306 // rmeove listeners !! important otherwise we kill the CPU
307 //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
308 //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
316 * write to stdin of process
317 * @arg str {String} string to write to stdin of process
318 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
320 private int write(string str) throws Error // write a line to
322 if (this.in_ch == null) {
323 return 0; // input is closed
325 //print("write: " + str);
326 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
329 var res = this.in_ch.write_chars(str.to_utf8(), out written);
331 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
333 if (res != GLib.IOStatus.NORMAL) {
334 throw new SpawnError.WRITE_ERROR("Write failed");
344 * read from pipe and call appropriate listerner and add to output or stderr string.
345 * @arg giochannel to read from.
348 private bool read(IOChannel ch)
350 string prop = (ch == this.out_ch) ? "output" : "stderr";
351 // print("prop: " + prop);
354 //print(JSON.stringify(ch, null,4));
361 status = ch.read_line( out buffer, out len, out term_pos );
368 // print('status: ' +JSON.stringify(status));
369 // print(JSON.stringify(x));
371 case GLib.IOStatus.NORMAL:
375 //if (this.listeners[prop]) {
376 // this.listeners[prop].call(this, x.str_return);
378 if (ch == this.out_ch) {
379 this.output += buffer;
380 this.output_line( buffer);
383 this.stderr += buffer;
385 //_this[prop] += x.str_return;
386 //if (this.cfg.debug) {
387 GLib.debug("%s : %s", prop , buffer);
391 //if ( Gtk.events_pending()) {
392 // Gtk.main_iteration();
397 //this.ctx.iteration(true);
399 case GLib.IOStatus.AGAIN:
400 //print("Should be called again.. waiting for more data..");
403 case GLib.IOStatus.ERROR:
404 case GLib.IOStatus.EOF:
412 //print("RETURNING");
413 return false; // allow it to be called again..
418 int main (string[] args) {
419 GLib.Log.set_handler(null,
420 GLib.LogLevelFlags.LEVEL_DEBUG | GLib.LogLevelFlags.LEVEL_WARNING,
422 print("%s: %s\n", dom, msg);
425 var ctx = new GLib.MainLoop ();
426 var a = new Spawn("", { "ls" , "-l"});
427 a.finish.connect((res, str, stderr) => {
433 ctx.run(); // wait for exit?