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();
48 public boolean exceptions; // fire exceptions.
49 public boolean debug; // fire exceptions.
51 public SpawnOutput output
52 public SpawnErr stderr;
53 public SpawnInput input;
55 public SpawnConfig() {
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";
108 boolean ctx = false; // the mainloop ctx.
111 * @property output {String} resulting output
115 * @property stderr {String} resulting output from stderr
119 * @property result {Number} execution result.
123 * @property pid {Number} pid of child process (of false if it's not running)
127 * @property in_ch {GLib.IOChannel} input io channel
129 IOChannel in_ch = null;
131 * @property out_ch {GLib.IOChannel} output io channel
133 IOChannel out_ch = null;
135 * @property err_ch {GLib.IOChannel} stderr io channel
137 IOChannel err_ch = null;
139 * @property err_src {int} the watch for errors
144 * @property err_src {int} the watch for output
151 * Run the configured command.
152 * result is applied to object properties (eg. 'output' or 'stderr')
153 * @returns {Object} self.
168 if (this.cfg.debug) {
169 print("cd " + this.cfg.cwd +";" + string.joinv(" ", this.cfg.args));
172 Process.spawn_async_with_pipes (
176 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
186 //print(JSON.stringify(gret));
188 if (this.cfg.debug) {
189 print("PID: " + this.pid);
192 ChildWatch.add (this.pid, (w_pid, result) => {
194 this.result = result;
196 print("child_watch_add : result: " + result);
199 this.read(this.out_ch);
200 this.read(this.err_ch);
203 Process.close_pid(this.pid);
209 //print("DONE TIDYUP");
210 if (this.cfg.finish) {
211 this.cfg.finish(this.result);
218 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
219 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
220 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
222 // make everything non-blocking!
226 // using NONBLOCKING only works if io_add_watch
227 //returns true/false in right conditions
228 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
229 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
230 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
234 // add handlers for output and stderr.
236 this.out_src = this.out_ch.add_watch (
237 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
238 (channel, condition) => {
239 return this.read(_this.out_ch);
242 this.err_src = this.err_ch.add_watch (
243 IOCondition.OUT | IOCondition.IN | IOCondition.PRI | IOCondition.HUP | IOCondition.ERR ,
244 (channel, condition) => {
245 return this.read(_this.err_ch);
252 // child can exit before 1we get this far..
253 if (this.cfg.input != null) {
254 if (this.cfg.debug) print("Trying to call listeners");
256 this.write(this.cfg.input());
257 // this probably needs to be a bit smarter...
258 //but... let's close input now..
271 // async - if running - return..
272 if (this.cfg.async && this.pid > -1) {
276 // start mainloop if not async..
279 if (this.cfg.debug) {
280 print("starting main loop");
282 this.ctx = new MainLoop ();
283 loop.run(); // wait fore exit?
285 //print("main_loop done!");
287 this.tidyup(); // tidyup get's called in main loop.
290 if (this.cfg.exceptions && this.result != 0) {
291 //this.toString = function() { return this.stderr; };
292 ///throw new Exception this; // we throw self...
295 // finally throw, or return self..
303 private void tidyup()
306 Process.close_pid(this.pid); // hopefully kills it..
309 if (this.in_ch) this.in_ch.close();
310 if (this.out_ch) this.out_ch.close();
311 if (this.err_ch) this.err_ch.close();
312 // blank out channels
316 // rmeove listeners !! important otherwise we kill the CPU
317 if (this.err_src !== false) GLib.source_remove(this.err_src);
318 if (this.out_src !== false) GLib.source_remove(this.out_src);
319 this.err_src = false;
320 this.out_src = false;
326 * write to stdin of process
327 * @arg str {String} string to write to stdin of process
328 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
330 integer write(str) // write a line to
332 if (this.in_ch is null) {
333 return 0; // input is closed
335 //print("write: " + str);
336 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
338 //var res = this.in_ch.write_chars(str, str.length, ret);
339 var res = this.in_ch.write_chars(str, str.length);
341 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
343 if (res != GLib.IOStatus.NORMAL) {
344 throw "Write failed";
352 * read from pipe and call appropriate listerner and add to output or stderr string.
353 * @arg giochannel to read from.
358 var prop = ch == this.out_ch ? 'output' : 'stderr';
359 // print("prop: " + prop);
363 //print(JSON.stringify(ch, null,4));
367 var status = ch.read_line( x);
368 // print('status: ' +JSON.stringify(status));
369 // print(JSON.stringify(x));
371 case GLib.IOStatus.NORMAL:
374 if (this.listeners[prop]) {
375 this.listeners[prop].call(this, x.str_return);
377 _this[prop] += x.str_return;
379 print(prop + ':' + x.str_return.replace(/\n/, ''));
383 if (imports.gi.Gtk.events_pending()) {
384 imports.gi.Gtk.main_iteration();
391 //this.ctx.iteration(true);
393 case GLib.IOStatus.AGAIN:
394 //print("Should be called again.. waiting for more data..");
397 case GLib.IOStatus.ERROR:
398 case GLib.IOStatus.EOF:
406 //print("RETURNING");
407 return false; // allow it to be called again..
415 args: ['ls', '/tmp'],
418 } catch (e) { print(JSON.stringify(e)); }
420 var secs = (new Date()).getSeconds()
424 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
427 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }