v / examples / process
Raw file | 74 loc (58 sloc) | 1.79 KB | Latest commit hash 017ace6ea
1module main
2
3import os
4
5// this is a example script to show you stdin can be used and keep a process open
6
7fn exec(cmd string) (string, int) {
8 mut cmd2 := cmd
9 mut out := ''
10 mut line := ''
11 mut rc := 0
12 mut p := os.new_process('/bin/bash')
13
14 // there are methods missing to know if stderr/stdout has data as such its better to redirect bot on same FD
15 // not so nice trick to run bash in bash and redirect stderr, maybe someone has a better solution
16 p.set_args(['-c', 'bash 2>&1'])
17 p.set_redirect_stdio()
18 p.run()
19
20 p.stdin_write('${cmd2} && echo **OK**')
21 os.fd_close(p.stdio_fd[0]) // important: close stdin so cmd can end by itself
22
23 for p.is_alive() {
24 line = p.stdout_read()
25 println(line)
26 // line_err = p.stderr_read() //IF WE CALL STDERR_READ will block
27 // we need a mechanism which allows us to check if stderr/stdout has data or it should never block
28 // is not a good way, need to use a string buffer, is slow like this
29 out += line
30 if line.ends_with('**OK**\n') {
31 out = out[0..(out.len - 7)]
32 break
33 }
34 }
35
36 // println("read from stdout, should not block")
37 // is not really needed but good test to see behaviour
38 out += p.stdout_read()
39 println('read done')
40
41 println(p.stderr_read())
42 p.close()
43 p.wait()
44 if p.code > 0 {
45 rc = 1
46 println('ERROR:')
47 println(cmd2)
48 print(out)
49 }
50
51 return out, rc
52}
53
54fn main() {
55 mut out := ''
56 mut rc := 0
57
58 // find files from /tmp excluding files unlistable by current user
59
60 out, rc = exec("find /tmp/ -user \$UID; echo '******'")
61 println(out)
62 assert out.ends_with('******\n')
63
64 out, rc = exec('echo to stdout')
65 assert out.contains('to stdout')
66
67 out, rc = exec('echo to stderr 1>&2')
68 assert out.contains('to stderr')
69
70 out, rc = exec('ls /sssss')
71 assert rc > 0 // THIS STILL GIVES AN ERROR !
72
73 println('test ok stderr & stdout is indeed redirected')
74}