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
24 * Spawn = import.Spawn;
27 * var output = new Spawn({
29 * args : [ 'ls', '-l' ],
30 * env : [], // optional
32 output : function (line) { Seed.print(line); },
33 * stderr : function (line) {Seed.print("ERROR" + line); },
34 * input : function() { return 'xxx' },
42 *var output = Spawn.run( SpawnConfig() {
43 cwd = "/home", // empty string to default to homedirectory.
46 ouput = (line) => { stdout.printf("%d\n", line); }
47 stderr = (line) => { stdout.printf("%d\n", line); }
48 input = () => { return "xxx"; }
53 delegate void SpawnOutput(string line);
54 delegate void SpawnErr(string line);
55 delegate string SpawnInput();
65 public boolean exceptions; // fire exceptions.
66 public boolean debug; // fire exceptions.
68 public SpawnOutput output
69 public SpawnErr stderr;
70 public SpawnInput input;
72 public SpawnConfig() {
88 * @param cfg {SpawnConfig} settings - see properties.
90 * @arg cwd {String} working directory. (defaults to home directory)
91 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
92 * @arg listeners {Object} (optional) handlers for output, stderr, input
93 * stderr/output both receive output line as argument
94 * input should return any standard input
95 * finish recieves result as argument.
96 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
97 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
98 * @arg exceptions {Boolean} throw exception on failure (default no)
99 * @arg debug {Boolean} print out what's going on.. (default no)
104 public class Spawn : Object
109 public Spawn(SpawnConfig cfg)
116 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
117 if (!this.cfg.args.length) {
118 throw "No arguments";
124 boolean ctx = false; // the mainloop ctx.
127 * @property output {String} resulting output
131 * @property stderr {String} resulting output from stderr
135 * @property result {Number} execution result.
139 * @property pid {Number} pid of child process (of false if it's not running)
143 * @property in_ch {GLib.IOChannel} input io channel
145 IOChannel in_ch = null;
147 * @property out_ch {GLib.IOChannel} output io channel
149 IOChannel out_ch = null;
151 * @property err_ch {GLib.IOChannel} stderr io channel
153 IOChannel err_ch = null;
155 * @property err_src {int} the watch for errors
160 * @property err_src {int} the watch for output
167 * Run the configured command.
168 * result is applied to object properties (eg. 'output' or 'stderr')
169 * @returns {Object} self.
184 if (this.cfg.debug) {
185 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
188 Process.spawn_async_with_pipes (
192 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
202 //print(JSON.stringify(gret));
204 if (this.cfg.debug) {
205 print("PID: " + this.pid);
208 ChildWatch.add (this.pid, (w_pid, result) => {
210 this.result = result;
212 print("child_watch_add : result: " + result);
215 this.read(this.out_ch);
216 this.read(this.err_ch);
219 Process.close_pid(this.pid);
225 //print("DONE TIDYUP");
226 if (this.cfg.finish) {
227 this.cfg.finish(this.result);
234 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
235 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
236 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
238 // make everything non-blocking!
242 // using NONBLOCKING only works if io_add_watch
243 //returns true/false in right conditions
244 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
245 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
246 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
250 // add handlers for output and stderr.
252 this.out_src = this.out_ch.add_watch (
253 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
254 (channel, condition) => {
255 return this.read(_this.out_ch);
258 this.err_src = this.err_ch.add_watch (
259 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
260 (channel, condition) => {
261 return this.read(_this.err_ch);
268 // child can exit before 1we get this far..
269 if (this.cfg.input != null) {
270 if (this.cfg.debug) print("Trying to call listeners");
272 this.write(this.cfg.input());
273 // this probably needs to be a bit smarter...
274 //but... let's close input now..
287 // async - if running - return..
288 if (this.cfg.async && this.pid > -1) {
292 // start mainloop if not async..
295 if (this.cfg.debug) {
296 print("starting main loop");
298 this.ctx = new MainLoop ();
299 loop.run(); // wait fore exit?
301 //print("main_loop done!");
303 this.tidyup(); // tidyup get's called in main loop.
306 if (this.cfg.exceptions && this.result != 0) {
307 //this.toString = function() { return this.stderr; };
308 ///throw new Exception this; // we throw self...
311 // finally throw, or return self..
319 private void tidyup()
322 Process.close_pid(this.pid); // hopefully kills it..
325 if (this.in_ch) this.in_ch.close();
326 if (this.out_ch) this.out_ch.close();
327 if (this.err_ch) this.err_ch.close();
328 // blank out channels
332 // rmeove listeners !! important otherwise we kill the CPU
333 if (this.err_src !== false) GLib.source_remove(this.err_src);
334 if (this.out_src !== false) GLib.source_remove(this.out_src);
335 this.err_src = false;
336 this.out_src = false;
342 * write to stdin of process
343 * @arg str {String} string to write to stdin of process
344 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
346 integer write(str) // write a line to
348 if (this.in_ch is null) {
349 return 0; // input is closed
351 //print("write: " + str);
352 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
354 //var res = this.in_ch.write_chars(str, str.length, ret);
355 var res = this.in_ch.write_chars(str, str.length);
357 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
359 if (res != GLib.IOStatus.NORMAL) {
360 throw "Write failed";
368 * read from pipe and call appropriate listerner and add to output or stderr string.
369 * @arg giochannel to read from.
374 var prop = ch == this.out_ch ? 'output' : 'stderr';
375 // print("prop: " + prop);
379 //print(JSON.stringify(ch, null,4));
383 var status = ch.read_line( x);
384 // print('status: ' +JSON.stringify(status));
385 // print(JSON.stringify(x));
387 case GLib.IOStatus.NORMAL:
390 if (this.listeners[prop]) {
391 this.listeners[prop].call(this, x.str_return);
393 _this[prop] += x.str_return;
395 print(prop + ':' + x.str_return.replace(/\n/, ''));
399 if (imports.gi.Gtk.events_pending()) {
400 imports.gi.Gtk.main_iteration();
407 //this.ctx.iteration(true);
409 case GLib.IOStatus.AGAIN:
410 //print("Should be called again.. waiting for more data..");
413 case GLib.IOStatus.ERROR:
414 case GLib.IOStatus.EOF:
422 //print("RETURNING");
423 return false; // allow it to be called again..
431 args: ['ls', '/tmp'],
434 } catch (e) { print(JSON.stringify(e)); }
436 var secs = (new Date()).getSeconds()
440 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
443 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }