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 = Spawn.run({
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() {
85 * @param cfg {SpawnConfig} settings - see properties.
87 * @arg cwd {String} working directory. (defaults to home directory)
88 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
89 * @arg listeners {Object} (optional) handlers for output, stderr, input
90 * stderr/output both receive output line as argument
91 * input should return any standard input
92 * finish recieves result as argument.
93 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
94 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
95 * @arg exceptions {Boolean} throw exception on failure (default no)
96 * @arg debug {Boolean} print out what's going on.. (default no)
101 public class Spawn : Object
106 public Spawn(SpawnConfig cfg)
113 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
114 if (!this.cfg.args.length) {
115 throw "No arguments";
121 boolean ctx = false; // the mainloop ctx.
124 * @property output {String} resulting output
128 * @property stderr {String} resulting output from stderr
132 * @property result {Number} execution result.
136 * @property pid {Number} pid of child process (of false if it's not running)
140 * @property in_ch {GLib.IOChannel} input io channel
142 IOChannel in_ch = null;
144 * @property out_ch {GLib.IOChannel} output io channel
146 IOChannel out_ch = null;
148 * @property err_ch {GLib.IOChannel} stderr io channel
150 IOChannel err_ch = null;
154 * Run the configured command.
155 * result is applied to object properties (eg. 'output' or 'stderr')
156 * @returns {Object} self.
158 public run : function()
166 if (this.cfg.debug) {
167 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
170 Process.spawn_async_with_pipes (
174 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
183 var gret = GLib.spawn_async_with_pipes(this.cwd, this.args, this.env,
184 GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH ,
188 if (typeof(Seed) == 'undefined') {
191 standard_input : gret[2],
192 standard_output: gret[3],
193 standard_error: gret[4]
198 //print(JSON.stringify(gret));
199 this.pid = ret.child_pid;
202 print("PID: " + this.pid);
207 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
208 _this.result = result;
210 print("child_watch_add : result: " + result);
212 _this.read(_this.out_ch);
213 _this.read(_this.err_ch);
216 GLib.spawn_close_pid(_this.pid);
222 //print("DONE TIDYUP");
223 if (_this.listeners.finish) {
224 _this.listeners.finish.call(this, _this.result);
231 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
234 if (_this.in_ch) _this.in_ch.close();
235 if (_this.out_ch) _this.out_ch.close();
236 if (_this.err_ch) _this.err_ch.close();
237 // blank out channels
239 _this.err_ch = false;
240 _this.out_ch = false;
241 // rmeove listeners !! important otherwise we kill the CPU
242 if (err_src !== false) GLib.source_remove(err_src);
243 if (out_src !== false) GLib.source_remove(out_src);
250 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
251 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
252 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
254 // make everything non-blocking!
258 // using NONBLOCKING only works if io_add_watch
259 //returns true/false in right conditions
260 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
261 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
262 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
266 // add handlers for output and stderr.
267 out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT,
268 GLib.IOCondition.OUT + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.HUP + GLib.IOCondition.ERR,
271 return _this.read(_this.out_ch);
275 err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT,
276 GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT + GLib.IOCondition.HUP,
279 return _this.read(_this.err_ch);
286 if (this.pid !== false) {
287 // child can exit before 1we get this far..
288 if (this.listeners.input) {
289 print("Trying to call listeners");
291 this.write(this.listeners.input.call(this));
292 // this probably needs to be a bit smarter...
293 //but... let's close input now..
309 // async - if running - return..
310 if (this.async && this.pid) {
314 // start mainloop if not async..
316 if (this.pid !== false) {
318 print("starting main loop");
321 this.ctx = isSeed ? new GLib.MainLoop.c_new (null, false) : GLib.MainLoop.new (null, false);;
322 this.ctx.run(false); // wait fore exit?
324 //print("main_loop done!");
326 tidyup(); // tidyup get's called in main loop.
329 if (this.exceptions && this.result != 0) {
330 this.toString = function() { return this.stderr; };
331 throw this; // we throw self...
334 // finally throw, or return self..
340 * write to stdin of process
341 * @arg str {String} string to write to stdin of process
342 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
344 write : function(str) // write a line to
347 return 0; // input is closed
349 //print("write: " + str);
350 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
352 //var res = this.in_ch.write_chars(str, str.length, ret);
353 var res = this.in_ch.write_chars(str, str.length);
355 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
357 if (res != GLib.IOStatus.NORMAL) {
358 throw "Write failed";
366 * read from pipe and call appropriate listerner and add to output or stderr string.
367 * @arg giochannel to read from.
372 var prop = ch == this.out_ch ? 'output' : 'stderr';
373 // print("prop: " + prop);
377 //print(JSON.stringify(ch, null,4));
381 var status = ch.read_line( x);
382 // print('status: ' +JSON.stringify(status));
383 // print(JSON.stringify(x));
385 case GLib.IOStatus.NORMAL:
388 if (this.listeners[prop]) {
389 this.listeners[prop].call(this, x.str_return);
391 _this[prop] += x.str_return;
393 print(prop + ':' + x.str_return.replace(/\n/, ''));
397 if (imports.gi.Gtk.events_pending()) {
398 imports.gi.Gtk.main_iteration();
405 //this.ctx.iteration(true);
407 case GLib.IOStatus.AGAIN:
408 //print("Should be called again.. waiting for more data..");
411 case GLib.IOStatus.ERROR:
412 case GLib.IOStatus.EOF:
420 //print("RETURNING");
421 return false; // allow it to be called again..
428 * simple run a process - returns result, or throws stderr result...
429 * @param cfg {Object} see spawn
430 * @return {string} stdout output.
433 cfg.exceptions = true;
435 var s = new Spawn(cfg);
443 args: ['ls', '/tmp'],
446 } catch (e) { print(JSON.stringify(e)); }
448 var secs = (new Date()).getSeconds()
452 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
455 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }