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();
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() {
70 * @param cfg {SpawnConfig} settings - see properties.
72 * @arg cwd {String} working directory. (defaults to home directory)
73 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
74 * @arg listeners {Object} (optional) handlers for output, stderr, input
75 * stderr/output both receive output line as argument
76 * input should return any standard input
77 * finish recieves result as argument.
78 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
79 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
80 * @arg exceptions {Boolean} throw exception on failure (default no)
81 * @arg debug {Boolean} print out what's going on.. (default no)
86 public class Spawn : Object
91 public Spawn(SpawnConfig cfg)
98 this.cwd = this.cfg.cwd.length || GLib.get_home_dir();
99 if (!this.cfg.args.length) {
100 throw "No arguments";
107 boolean ctx = false; // the mainloop ctx.
110 * @property output {String} resulting output
114 * @property stderr {String} resulting output from stderr
118 * @property result {Number} execution result.
122 * @property pid {Number} pid of child process (of false if it's not running)
126 * @property in_ch {GLib.IOChannel} input io channel
128 IOChannel in_ch = null;
130 * @property out_ch {GLib.IOChannel} output io channel
132 IOChannel out_ch = null;
134 * @property err_ch {GLib.IOChannel} stderr io channel
136 IOChannel err_ch = null;
138 * @property err_src {int} the watch for errors
143 * @property err_src {int} the watch for output
150 * Run the configured command.
151 * result is applied to object properties (eg. 'output' or 'stderr')
152 * @returns {Object} self.
167 if (this.cfg.debug) {
168 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
171 Process.spawn_async_with_pipes (
175 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
185 //print(JSON.stringify(gret));
187 if (this.cfg.debug) {
188 print("PID: " + this.pid);
191 ChildWatch.add (this.pid, (w_pid, result) => {
193 this.result = result;
195 print("child_watch_add : result: " + result);
198 this.read(this.out_ch);
199 this.read(this.err_ch);
202 Process.close_pid(this.pid);
208 //print("DONE TIDYUP");
209 if (this.cfg.finish) {
210 this.cfg.finish(this.result);
217 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
218 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
219 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
221 // make everything non-blocking!
225 // using NONBLOCKING only works if io_add_watch
226 //returns true/false in right conditions
227 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
228 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
229 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
233 // add handlers for output and stderr.
235 this.out_src = this.out_ch.add_watch (
236 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
237 (channel, condition) => {
238 return this.read(_this.out_ch);
241 this.err_src = this.err_ch.add_watch (
242 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
243 (channel, condition) => {
244 return this.read(_this.err_ch);
251 // child can exit before 1we get this far..
252 if (this.cfg.input != null) {
253 if (this.cfg.debug) print("Trying to call listeners");
255 this.write(this.cfg.input());
256 // this probably needs to be a bit smarter...
257 //but... let's close input now..
270 // async - if running - return..
271 if (this.cfg.async && this.pid > -1) {
275 // start mainloop if not async..
278 if (this.cfg.debug) {
279 print("starting main loop");
281 this.ctx = new MainLoop ();
282 loop.run(); // wait fore exit?
284 //print("main_loop done!");
286 this.tidyup(); // tidyup get's called in main loop.
289 if (this.cfg.exceptions && this.result != 0) {
290 //this.toString = function() { return this.stderr; };
291 ///throw new Exception this; // we throw self...
294 // finally throw, or return self..
302 private void tidyup()
305 Process.close_pid(this.pid); // hopefully kills it..
308 if (this.in_ch) this.in_ch.close();
309 if (this.out_ch) this.out_ch.close();
310 if (this.err_ch) this.err_ch.close();
311 // blank out channels
315 // rmeove listeners !! important otherwise we kill the CPU
316 if (this.err_src !== false) GLib.source_remove(this.err_src);
317 if (this.out_src !== false) GLib.source_remove(this.out_src);
318 this.err_src = false;
319 this.out_src = false;
325 * write to stdin of process
326 * @arg str {String} string to write to stdin of process
327 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
329 integer write(str) // write a line to
331 if (this.in_ch is null) {
332 return 0; // input is closed
334 //print("write: " + str);
335 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
337 //var res = this.in_ch.write_chars(str, str.length, ret);
338 var res = this.in_ch.write_chars(str, str.length);
340 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
342 if (res != GLib.IOStatus.NORMAL) {
343 throw "Write failed";
351 * read from pipe and call appropriate listerner and add to output or stderr string.
352 * @arg giochannel to read from.
357 var prop = ch == this.out_ch ? 'output' : 'stderr';
358 // print("prop: " + prop);
362 //print(JSON.stringify(ch, null,4));
366 var status = ch.read_line( x);
367 // print('status: ' +JSON.stringify(status));
368 // print(JSON.stringify(x));
370 case GLib.IOStatus.NORMAL:
373 if (this.listeners[prop]) {
374 this.listeners[prop].call(this, x.str_return);
376 _this[prop] += x.str_return;
378 print(prop + ':' + x.str_return.replace(/\n/, ''));
382 if (imports.gi.Gtk.events_pending()) {
383 imports.gi.Gtk.main_iteration();
390 //this.ctx.iteration(true);
392 case GLib.IOStatus.AGAIN:
393 //print("Should be called again.. waiting for more data..");
396 case GLib.IOStatus.ERROR:
397 case GLib.IOStatus.EOF:
405 //print("RETURNING");
406 return false; // allow it to be called again..
414 args: ['ls', '/tmp'],
417 } catch (e) { print(JSON.stringify(e)); }
419 var secs = (new Date()).getSeconds()
423 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
426 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }