examples: fix process_stdin_trick example (#13953)

pull/13969/head
Pascal Masschelier 2022-04-07 12:55:12 +02:00 committed by GitHub
parent 6a820c2845
commit 95753ffb30
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 11 additions and 20 deletions

View File

@ -17,24 +17,17 @@ fn exec(cmd string) (string, int) {
p.set_redirect_stdio() p.set_redirect_stdio()
p.run() p.run()
if !cmd2.ends_with('\n') { p.stdin_write('$cmd2 && echo **OK**')
cmd2 += '\n' os.fd_close(p.stdio_fd[0]) // important: close stdin so cmd can end by itself
}
p.stdin_write(cmd2) for p.is_alive() {
p.stdin_write('\necho **OK**\n')
for {
if !p.is_alive() {
break
}
line = p.stdout_read() line = p.stdout_read()
println(line) println(line)
// line_err = p.stderr_read() //IF WE CALL STDERR_READ will block // line_err = p.stderr_read() //IF WE CALL STDERR_READ will block
// we need a mechanism which allows us to check if stderr/stdout has data or it should never block // we need a mechanism which allows us to check if stderr/stdout has data or it should never block
// is not a good way, need to use a string buffer, is slow like this // is not a good way, need to use a string buffer, is slow like this
out += line out += line
if out.ends_with('**OK**\n') { if line.ends_with('**OK**\n') {
out = out[0..(out.len - 7)] out = out[0..(out.len - 7)]
break break
} }
@ -42,19 +35,18 @@ fn exec(cmd string) (string, int) {
// println("read from stdout, should not block") // println("read from stdout, should not block")
// is not really needed but good test to see behaviour // is not really needed but good test to see behaviour
// out += p.stdout_read() out += p.stdout_read()
// println("read done") println('read done')
// println(cmd.stderr_read())
println(p.stderr_read())
p.close()
p.wait()
if p.code > 0 { if p.code > 0 {
rc = 1 rc = 1
println('ERROR:') println('ERROR:')
println(cmd2) println(cmd2)
print(out) print(out)
} }
// documentation says we need to call p.wait(), but this does not seem to work, will be process stop or become zombie?
// p.wait()
return out, rc return out, rc
} }
@ -63,10 +55,9 @@ fn main() {
mut out := '' mut out := ''
mut rc := 0 mut rc := 0
// the following does not work, not sure why not // find files from /tmp excluding files unlistable by current user
// out,rc = exec("find /tmp/ && echo '******'")
out, rc = exec("find /tmp/ ; echo '******'") out, rc = exec("find /tmp/ -user \$UID; echo '******'")
println(out) println(out)
assert out.ends_with('******\n') assert out.ends_with('******\n')