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() {
66 public setCommand(string cwd,
80 this.exceptions = exceptions;
98 * @param cfg {SpawnConfig} settings - see properties.
100 * @arg cwd {String} working directory. (defaults to home directory)
101 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
102 * @arg listeners {Object} (optional) handlers for output, stderr, input
103 * stderr/output both receive output line as argument
104 * input should return any standard input
105 * finish recieves result as argument.
106 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
107 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
108 * @arg exceptions {Boolean} throw exception on failure (default no)
109 * @arg debug {Boolean} print out what's going on.. (default no)
114 public class Spawn : Object
119 public Spawn(SpawnConfig cfg)
126 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
127 if (!this.cfg.args.length) {
128 throw "No arguments";
135 boolean ctx = false; // the mainloop ctx.
138 * @property output {String} resulting output
142 * @property stderr {String} resulting output from stderr
146 * @property result {Number} execution result.
150 * @property pid {Number} pid of child process (of false if it's not running)
154 * @property in_ch {GLib.IOChannel} input io channel
156 IOChannel in_ch = null;
158 * @property out_ch {GLib.IOChannel} output io channel
160 IOChannel out_ch = null;
162 * @property err_ch {GLib.IOChannel} stderr io channel
164 IOChannel err_ch = null;
166 * @property err_src {int} the watch for errors
171 * @property err_src {int} the watch for output
178 * Run the configured command.
179 * result is applied to object properties (eg. 'output' or 'stderr')
180 * @returns {Object} self.
195 if (this.cfg.debug) {
196 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
199 Process.spawn_async_with_pipes (
203 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
213 //print(JSON.stringify(gret));
215 if (this.cfg.debug) {
216 print("PID: " + this.pid);
219 ChildWatch.add (this.pid, (w_pid, result) => {
221 this.result = result;
223 print("child_watch_add : result: " + result);
226 this.read(this.out_ch);
227 this.read(this.err_ch);
230 Process.close_pid(this.pid);
236 //print("DONE TIDYUP");
237 if (this.cfg.finish) {
238 this.cfg.finish(this.result);
245 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
246 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
247 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
249 // make everything non-blocking!
253 // using NONBLOCKING only works if io_add_watch
254 //returns true/false in right conditions
255 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
256 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
257 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
261 // add handlers for output and stderr.
263 this.out_src = this.out_ch.add_watch (
264 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
265 (channel, condition) => {
266 return this.read(_this.out_ch);
269 this.err_src = this.err_ch.add_watch (
270 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
271 (channel, condition) => {
272 return this.read(_this.err_ch);
279 // child can exit before 1we get this far..
280 if (this.cfg.input != null) {
281 if (this.cfg.debug) print("Trying to call listeners");
283 this.write(this.cfg.input());
284 // this probably needs to be a bit smarter...
285 //but... let's close input now..
298 // async - if running - return..
299 if (this.cfg.async && this.pid > -1) {
303 // start mainloop if not async..
306 if (this.cfg.debug) {
307 print("starting main loop");
309 this.ctx = new MainLoop ();
310 loop.run(); // wait fore exit?
312 //print("main_loop done!");
314 this.tidyup(); // tidyup get's called in main loop.
317 if (this.cfg.exceptions && this.result != 0) {
318 //this.toString = function() { return this.stderr; };
319 ///throw new Exception this; // we throw self...
322 // finally throw, or return self..
330 private void tidyup()
333 Process.close_pid(this.pid); // hopefully kills it..
336 if (this.in_ch) this.in_ch.close();
337 if (this.out_ch) this.out_ch.close();
338 if (this.err_ch) this.err_ch.close();
339 // blank out channels
343 // rmeove listeners !! important otherwise we kill the CPU
344 if (this.err_src !== false) GLib.source_remove(this.err_src);
345 if (this.out_src !== false) GLib.source_remove(this.out_src);
346 this.err_src = false;
347 this.out_src = false;
353 * write to stdin of process
354 * @arg str {String} string to write to stdin of process
355 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
357 integer write(str) // write a line to
359 if (this.in_ch is null) {
360 return 0; // input is closed
362 //print("write: " + str);
363 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
365 //var res = this.in_ch.write_chars(str, str.length, ret);
366 var res = this.in_ch.write_chars(str, str.length);
368 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
370 if (res != GLib.IOStatus.NORMAL) {
371 throw "Write failed";
379 * read from pipe and call appropriate listerner and add to output or stderr string.
380 * @arg giochannel to read from.
385 var prop = ch == this.out_ch ? 'output' : 'stderr';
386 // print("prop: " + prop);
390 //print(JSON.stringify(ch, null,4));
394 var status = ch.read_line( x);
395 // print('status: ' +JSON.stringify(status));
396 // print(JSON.stringify(x));
398 case GLib.IOStatus.NORMAL:
401 if (this.listeners[prop]) {
402 this.listeners[prop].call(this, x.str_return);
404 _this[prop] += x.str_return;
406 print(prop + ':' + x.str_return.replace(/\n/, ''));
410 if (imports.gi.Gtk.events_pending()) {
411 imports.gi.Gtk.main_iteration();
418 //this.ctx.iteration(true);
420 case GLib.IOStatus.AGAIN:
421 //print("Should be called again.. waiting for more data..");
424 case GLib.IOStatus.ERROR:
425 case GLib.IOStatus.EOF:
433 //print("RETURNING");
434 return false; // allow it to be called again..
442 args: ['ls', '/tmp'],
445 } catch (e) { print(JSON.stringify(e)); }
447 var secs = (new Date()).getSeconds()
451 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
454 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }