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();
64 public SpawnOutput output
65 public SpawnErr stderr;
66 public SpawnInput input;
71 * @param cfg {SpawnConfig} settings - see properties.
73 * @arg cwd {String} working directory. (defaults to home directory)
74 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
75 * @arg listeners {Object} (optional) handlers for output, stderr, input
76 * stderr/output both receive output line as argument
77 * input should return any standard input
78 * finish recieves result as argument.
79 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
80 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
81 * @arg exceptions {Boolean} throw exception on failure (default no)
82 * @arg debug {Boolean} print out what's going on.. (default no)
87 public class Spawn : Object
92 public Spawn(SpawnConfig cfg)
99 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
100 if (!this.cfg.args.length) {
101 throw "No arguments";
109 ctx : false, // the mainloop ctx.
118 * @property output {String} resulting output
122 * @property stderr {String} resulting output from stderr
126 * @property result {Number} execution result.
130 * @property pid {Number} pid of child process (of false if it's not running)
134 * @property in_ch {GLib.IOChannel} input io channel
138 * @property out_ch {GLib.IOChannel} output io channel
142 * @property err_ch {GLib.IOChannel} stderr io channel
148 * Run the configured command.
149 * result is applied to object properties (eg. 'output' or 'stderr')
150 * @returns {Object} self.
162 print("cd " + this.cwd +";" + this.args.join(" "));
165 var gret = GLib.spawn_async_with_pipes(this.cwd, this.args, this.env,
166 GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH ,
170 if (typeof(Seed) == 'undefined') {
173 standard_input : gret[2],
174 standard_output: gret[3],
175 standard_error: gret[4]
180 //print(JSON.stringify(gret));
181 this.pid = ret.child_pid;
184 print("PID: " + this.pid);
189 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
190 _this.result = result;
192 print("child_watch_add : result: " + result);
194 _this.read(_this.out_ch);
195 _this.read(_this.err_ch);
198 GLib.spawn_close_pid(_this.pid);
204 //print("DONE TIDYUP");
205 if (_this.listeners.finish) {
206 _this.listeners.finish.call(this, _this.result);
213 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
216 if (_this.in_ch) _this.in_ch.close();
217 if (_this.out_ch) _this.out_ch.close();
218 if (_this.err_ch) _this.err_ch.close();
219 // blank out channels
221 _this.err_ch = false;
222 _this.out_ch = false;
223 // rmeove listeners !! important otherwise we kill the CPU
224 if (err_src !== false) GLib.source_remove(err_src);
225 if (out_src !== false) GLib.source_remove(out_src);
232 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
233 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
234 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
236 // make everything non-blocking!
240 // using NONBLOCKING only works if io_add_watch
241 //returns true/false in right conditions
242 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
243 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
244 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
248 // add handlers for output and stderr.
249 out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT,
250 GLib.IOCondition.OUT + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.HUP + GLib.IOCondition.ERR,
253 return _this.read(_this.out_ch);
257 err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT,
258 GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT + GLib.IOCondition.HUP,
261 return _this.read(_this.err_ch);
268 if (this.pid !== false) {
269 // child can exit before 1we get this far..
270 if (this.listeners.input) {
271 print("Trying to call listeners");
273 this.write(this.listeners.input.call(this));
274 // this probably needs to be a bit smarter...
275 //but... let's close input now..
291 // async - if running - return..
292 if (this.async && this.pid) {
296 // start mainloop if not async..
298 if (this.pid !== false) {
300 print("starting main loop");
303 this.ctx = isSeed ? new GLib.MainLoop.c_new (null, false) : GLib.MainLoop.new (null, false);;
304 this.ctx.run(false); // wait fore exit?
306 //print("main_loop done!");
308 tidyup(); // tidyup get's called in main loop.
311 if (this.exceptions && this.result != 0) {
312 this.toString = function() { return this.stderr; };
313 throw this; // we throw self...
316 // finally throw, or return self..
322 * write to stdin of process
323 * @arg str {String} string to write to stdin of process
324 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
326 write : function(str) // write a line to
329 return 0; // input is closed
331 //print("write: " + str);
332 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
334 //var res = this.in_ch.write_chars(str, str.length, ret);
335 var res = this.in_ch.write_chars(str, str.length);
337 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
339 if (res != GLib.IOStatus.NORMAL) {
340 throw "Write failed";
348 * read from pipe and call appropriate listerner and add to output or stderr string.
349 * @arg giochannel to read from.
354 var prop = ch == this.out_ch ? 'output' : 'stderr';
355 // print("prop: " + prop);
359 //print(JSON.stringify(ch, null,4));
363 var status = ch.read_line( x);
364 // print('status: ' +JSON.stringify(status));
365 // print(JSON.stringify(x));
367 case GLib.IOStatus.NORMAL:
370 if (this.listeners[prop]) {
371 this.listeners[prop].call(this, x.str_return);
373 _this[prop] += x.str_return;
375 print(prop + ':' + x.str_return.replace(/\n/, ''));
379 if (imports.gi.Gtk.events_pending()) {
380 imports.gi.Gtk.main_iteration();
387 //this.ctx.iteration(true);
389 case GLib.IOStatus.AGAIN:
390 //print("Should be called again.. waiting for more data..");
393 case GLib.IOStatus.ERROR:
394 case GLib.IOStatus.EOF:
402 //print("RETURNING");
403 return false; // allow it to be called again..
410 * simple run a process - returns result, or throws stderr result...
411 * @param cfg {Object} see spawn
412 * @return {string} stdout output.
415 cfg.exceptions = true;
417 var s = new Spawn(cfg);
425 args: ['ls', '/tmp'],
428 } catch (e) { print(JSON.stringify(e)); }
430 var secs = (new Date()).getSeconds()
434 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
437 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }