3 ///using Gee; // for array list?
5 static int main (string[] args) {
6 // A reference to our file
8 var cfg = new SpawnConfig(null, { "ls" } , "");
9 var spawn = new Spawn(cfg);
12 var file = File.new_for_path ("data.txt");
18 var Gio = imports.gi.Gio;
19 var GLib = imports.gi.GLib;
25 * Library to wrap GLib.spawn_async_with_pipes
30 *var output = new Spawn( SpawnConfig() {
31 cwd = "/home", // empty string to default to homedirectory.
34 ouput = (line) => { stdout.printf("%d\n", line); }
35 stderr = (line) => { stdout.printf("%d\n", line); }
36 input = () => { return "xxx"; }
41 delegate void SpawnOutput(string line);
42 delegate void SpawnErr(string line);
43 delegate string SpawnInput();
47 public class SpawnConfig {
52 public boolean exceptions; // fire exceptions.
53 public boolean debug; // fire exceptions.
55 public SpawnOutput output
56 public SpawnErr stderr;
57 public SpawnInput input;
59 public SpawnConfig(string cwd,
84 this.exceptions = exceptions;
102 * @param cfg {SpawnConfig} settings - see properties.
104 * @arg cwd {String} working directory. (defaults to home directory)
105 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
106 * @arg listeners {Object} (optional) handlers for output, stderr, input
107 * stderr/output both receive output line as argument
108 * input should return any standard input
109 * finish recieves result as argument.
110 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
111 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
112 * @arg exceptions {Boolean} throw exception on failure (default no)
113 * @arg debug {Boolean} print out what's going on.. (default no)
118 public class Spawn : Object
123 public Spawn(SpawnConfig cfg)
130 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
131 if (!this.cfg.args.length) {
132 throw "No arguments";
139 boolean ctx = false; // the mainloop ctx.
142 * @property output {String} resulting output
146 * @property stderr {String} resulting output from stderr
150 * @property result {Number} execution result.
154 * @property pid {Number} pid of child process (of false if it's not running)
158 * @property in_ch {GLib.IOChannel} input io channel
160 IOChannel in_ch = null;
162 * @property out_ch {GLib.IOChannel} output io channel
164 IOChannel out_ch = null;
166 * @property err_ch {GLib.IOChannel} stderr io channel
168 IOChannel err_ch = null;
170 * @property err_src {int} the watch for errors
175 * @property err_src {int} the watch for output
182 * Run the configured command.
183 * result is applied to object properties (eg. 'output' or 'stderr')
184 * @returns {Object} self.
199 if (this.cfg.debug) {
200 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
203 Process.spawn_async_with_pipes (
207 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
217 //print(JSON.stringify(gret));
219 if (this.cfg.debug) {
220 print("PID: " + this.pid);
223 ChildWatch.add (this.pid, (w_pid, result) => {
225 this.result = result;
227 print("child_watch_add : result: " + result);
230 this.read(this.out_ch);
231 this.read(this.err_ch);
234 Process.close_pid(this.pid);
240 //print("DONE TIDYUP");
241 if (this.cfg.finish) {
242 this.cfg.finish(this.result);
249 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
250 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
251 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
253 // make everything non-blocking!
257 // using NONBLOCKING only works if io_add_watch
258 //returns true/false in right conditions
259 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
260 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
261 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
265 // add handlers for output and stderr.
267 this.out_src = this.out_ch.add_watch (
268 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
269 (channel, condition) => {
270 return this.read(_this.out_ch);
273 this.err_src = this.err_ch.add_watch (
274 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
275 (channel, condition) => {
276 return this.read(_this.err_ch);
283 // child can exit before 1we get this far..
284 if (this.cfg.input != null) {
285 if (this.cfg.debug) print("Trying to call listeners");
287 this.write(this.cfg.input());
288 // this probably needs to be a bit smarter...
289 //but... let's close input now..
302 // async - if running - return..
303 if (this.cfg.async && this.pid > -1) {
307 // start mainloop if not async..
310 if (this.cfg.debug) {
311 print("starting main loop");
313 this.ctx = new MainLoop ();
314 loop.run(); // wait fore exit?
316 //print("main_loop done!");
318 this.tidyup(); // tidyup get's called in main loop.
321 if (this.cfg.exceptions && this.result != 0) {
322 //this.toString = function() { return this.stderr; };
323 ///throw new Exception this; // we throw self...
326 // finally throw, or return self..
334 private void tidyup()
337 Process.close_pid(this.pid); // hopefully kills it..
340 if (this.in_ch) this.in_ch.close();
341 if (this.out_ch) this.out_ch.close();
342 if (this.err_ch) this.err_ch.close();
343 // blank out channels
347 // rmeove listeners !! important otherwise we kill the CPU
348 if (this.err_src !== false) GLib.source_remove(this.err_src);
349 if (this.out_src !== false) GLib.source_remove(this.out_src);
350 this.err_src = false;
351 this.out_src = false;
357 * write to stdin of process
358 * @arg str {String} string to write to stdin of process
359 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
361 integer write(str) // write a line to
363 if (this.in_ch is null) {
364 return 0; // input is closed
366 //print("write: " + str);
367 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
369 //var res = this.in_ch.write_chars(str, str.length, ret);
370 var res = this.in_ch.write_chars(str, str.length);
372 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
374 if (res != GLib.IOStatus.NORMAL) {
375 throw "Write failed";
383 * read from pipe and call appropriate listerner and add to output or stderr string.
384 * @arg giochannel to read from.
389 var prop = ch == this.out_ch ? 'output' : 'stderr';
390 // print("prop: " + prop);
394 //print(JSON.stringify(ch, null,4));
398 var status = ch.read_line( x);
399 // print('status: ' +JSON.stringify(status));
400 // print(JSON.stringify(x));
402 case GLib.IOStatus.NORMAL:
405 if (this.listeners[prop]) {
406 this.listeners[prop].call(this, x.str_return);
408 _this[prop] += x.str_return;
410 print(prop + ':' + x.str_return.replace(/\n/, ''));
414 if (imports.gi.Gtk.events_pending()) {
415 imports.gi.Gtk.main_iteration();
422 //this.ctx.iteration(true);
424 case GLib.IOStatus.AGAIN:
425 //print("Should be called again.. waiting for more data..");
428 case GLib.IOStatus.ERROR:
429 case GLib.IOStatus.EOF:
437 //print("RETURNING");
438 return false; // allow it to be called again..
446 args: ['ls', '/tmp'],
449 } catch (e) { print(JSON.stringify(e)); }
451 var secs = (new Date()).getSeconds()
455 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
458 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }