| 1 | module main |
| 2 | |
| 3 | import os |
| 4 | |
| 5 | // a test where we execute a bash script but work around where we put script in bash inside bash |
| 6 | |
| 7 | fn exec(path string, redirect bool) { |
| 8 | mut line := '' |
| 9 | mut line_err := '' |
| 10 | mut cmd := os.new_process('/bin/bash') |
| 11 | |
| 12 | if redirect { |
| 13 | cmd.set_args(['-c', '/bin/bash /tmp/test.sh 2>&1']) |
| 14 | } else { |
| 15 | cmd.set_args([path]) |
| 16 | } |
| 17 | |
| 18 | cmd.set_redirect_stdio() |
| 19 | cmd.run() |
| 20 | for cmd.is_alive() { |
| 21 | line = cmd.stdout_read() |
| 22 | println('STDOUT: ${line}') |
| 23 | |
| 24 | if !redirect { |
| 25 | line_err = cmd.stderr_read() |
| 26 | println('STDERR: ${line_err}') |
| 27 | } |
| 28 | } |
| 29 | if cmd.code > 0 { |
| 30 | println('ERROR:') |
| 31 | println(cmd) |
| 32 | // println(cmd.stderr_read()) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | fn main() { |
| 37 | script := ' |
| 38 | echo line 1 |
| 39 | #will use some stderr now |
| 40 | echo redirect 1 to 2 1>&2 |
| 41 | echo line 3 |
| 42 | ' |
| 43 | |
| 44 | os.write_file('/tmp/test.sh', script) or { panic(err) } |
| 45 | // os.chmod("/tmp/test.sh",0o700) //make executable |
| 46 | |
| 47 | // this will work because stderr/stdout are smaller than 4096 chars, once larger there can be deadlocks |
| 48 | // in other words this can never work reliably without being able to check if there is data on stderr or stdout |
| 49 | exec('/tmp/test.sh', false) |
| 50 | |
| 51 | // this will always work |
| 52 | exec('/tmp/test.sh', true) |
| 53 | } |
| 54 | |