3 ///using Gee; // for array list?
5 static int main (string[] args) {
6 // A reference to our file
7 var file = File.new_for_path ("data.txt");
13 var Gio = imports.gi.Gio;
14 var GLib = imports.gi.GLib;
20 * Library to wrap GLib.spawn_async_with_pipes
25 *var output = new Spawn( SpawnConfig() {
26 cwd = "/home", // empty string to default to homedirectory.
29 ouput = (line) => { stdout.printf("%d\n", line); }
30 stderr = (line) => { stdout.printf("%d\n", line); }
31 input = () => { return "xxx"; }
36 delegate void SpawnOutput(string line);
37 delegate void SpawnErr(string line);
38 delegate string SpawnInput();
42 public class SpawnConfig {
47 public boolean exceptions; // fire exceptions.
48 public boolean debug; // fire exceptions.
50 public SpawnOutput output
51 public SpawnErr stderr;
52 public SpawnInput input;
54 public SpawnConfig(string cwd,
79 this.exceptions = exceptions;
97 * @param cfg {SpawnConfig} settings - see properties.
99 * @arg cwd {String} working directory. (defaults to home directory)
100 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
101 * @arg listeners {Object} (optional) handlers for output, stderr, input
102 * stderr/output both receive output line as argument
103 * input should return any standard input
104 * finish recieves result as argument.
105 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
106 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
107 * @arg exceptions {Boolean} throw exception on failure (default no)
108 * @arg debug {Boolean} print out what's going on.. (default no)
113 public class Spawn : Object
118 public Spawn(SpawnConfig cfg)
125 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
126 if (!this.cfg.args.length) {
127 throw "No arguments";
134 boolean ctx = false; // the mainloop ctx.
137 * @property output {String} resulting output
141 * @property stderr {String} resulting output from stderr
145 * @property result {Number} execution result.
149 * @property pid {Number} pid of child process (of false if it's not running)
153 * @property in_ch {GLib.IOChannel} input io channel
155 IOChannel in_ch = null;
157 * @property out_ch {GLib.IOChannel} output io channel
159 IOChannel out_ch = null;
161 * @property err_ch {GLib.IOChannel} stderr io channel
163 IOChannel err_ch = null;
165 * @property err_src {int} the watch for errors
170 * @property err_src {int} the watch for output
177 * Run the configured command.
178 * result is applied to object properties (eg. 'output' or 'stderr')
179 * @returns {Object} self.
194 if (this.cfg.debug) {
195 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
198 Process.spawn_async_with_pipes (
202 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
212 //print(JSON.stringify(gret));
214 if (this.cfg.debug) {
215 print("PID: " + this.pid);
218 ChildWatch.add (this.pid, (w_pid, result) => {
220 this.result = result;
222 print("child_watch_add : result: " + result);
225 this.read(this.out_ch);
226 this.read(this.err_ch);
229 Process.close_pid(this.pid);
235 //print("DONE TIDYUP");
236 if (this.cfg.finish) {
237 this.cfg.finish(this.result);
244 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
245 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
246 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
248 // make everything non-blocking!
252 // using NONBLOCKING only works if io_add_watch
253 //returns true/false in right conditions
254 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
255 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
256 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
260 // add handlers for output and stderr.
262 this.out_src = this.out_ch.add_watch (
263 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
264 (channel, condition) => {
265 return this.read(_this.out_ch);
268 this.err_src = this.err_ch.add_watch (
269 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
270 (channel, condition) => {
271 return this.read(_this.err_ch);
278 // child can exit before 1we get this far..
279 if (this.cfg.input != null) {
280 if (this.cfg.debug) print("Trying to call listeners");
282 this.write(this.cfg.input());
283 // this probably needs to be a bit smarter...
284 //but... let's close input now..
297 // async - if running - return..
298 if (this.cfg.async && this.pid > -1) {
302 // start mainloop if not async..
305 if (this.cfg.debug) {
306 print("starting main loop");
308 this.ctx = new MainLoop ();
309 loop.run(); // wait fore exit?
311 //print("main_loop done!");
313 this.tidyup(); // tidyup get's called in main loop.
316 if (this.cfg.exceptions && this.result != 0) {
317 //this.toString = function() { return this.stderr; };
318 ///throw new Exception this; // we throw self...
321 // finally throw, or return self..
329 private void tidyup()
332 Process.close_pid(this.pid); // hopefully kills it..
335 if (this.in_ch) this.in_ch.close();
336 if (this.out_ch) this.out_ch.close();
337 if (this.err_ch) this.err_ch.close();
338 // blank out channels
342 // rmeove listeners !! important otherwise we kill the CPU
343 if (this.err_src !== false) GLib.source_remove(this.err_src);
344 if (this.out_src !== false) GLib.source_remove(this.out_src);
345 this.err_src = false;
346 this.out_src = false;
352 * write to stdin of process
353 * @arg str {String} string to write to stdin of process
354 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
356 integer write(str) // write a line to
358 if (this.in_ch is null) {
359 return 0; // input is closed
361 //print("write: " + str);
362 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
364 //var res = this.in_ch.write_chars(str, str.length, ret);
365 var res = this.in_ch.write_chars(str, str.length);
367 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
369 if (res != GLib.IOStatus.NORMAL) {
370 throw "Write failed";
378 * read from pipe and call appropriate listerner and add to output or stderr string.
379 * @arg giochannel to read from.
384 var prop = ch == this.out_ch ? 'output' : 'stderr';
385 // print("prop: " + prop);
389 //print(JSON.stringify(ch, null,4));
393 var status = ch.read_line( x);
394 // print('status: ' +JSON.stringify(status));
395 // print(JSON.stringify(x));
397 case GLib.IOStatus.NORMAL:
400 if (this.listeners[prop]) {
401 this.listeners[prop].call(this, x.str_return);
403 _this[prop] += x.str_return;
405 print(prop + ':' + x.str_return.replace(/\n/, ''));
409 if (imports.gi.Gtk.events_pending()) {
410 imports.gi.Gtk.main_iteration();
417 //this.ctx.iteration(true);
419 case GLib.IOStatus.AGAIN:
420 //print("Should be called again.. waiting for more data..");
423 case GLib.IOStatus.ERROR:
424 case GLib.IOStatus.EOF:
432 //print("RETURNING");
433 return false; // allow it to be called again..
441 args: ['ls', '/tmp'],
444 } catch (e) { print(JSON.stringify(e)); }
446 var secs = (new Date()).getSeconds()
450 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
453 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }