1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

examples: fix process_stdin_trick example (#13953)

This commit is contained in:
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

View File

@ -17,24 +17,17 @@ fn exec(cmd string) (string, int) {
p.set_redirect_stdio()
p.run()
if !cmd2.ends_with('\n') {
cmd2 += '\n'
}
p.stdin_write('$cmd2 && echo **OK**')
os.fd_close(p.stdio_fd[0]) // important: close stdin so cmd can end by itself
p.stdin_write(cmd2)
p.stdin_write('\necho **OK**\n')
for {
if !p.is_alive() {
break
}
for p.is_alive() {
line = p.stdout_read()
println(line)
// 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
// is not a good way, need to use a string buffer, is slow like this
out += line
if out.ends_with('**OK**\n') {
if line.ends_with('**OK**\n') {
out = out[0..(out.len - 7)]
break
}
@ -42,19 +35,18 @@ fn exec(cmd string) (string, int) {
// println("read from stdout, should not block")
// is not really needed but good test to see behaviour
// out += p.stdout_read()
// println("read done")
// println(cmd.stderr_read())
out += p.stdout_read()
println('read done')
println(p.stderr_read())
p.close()
p.wait()
if p.code > 0 {
rc = 1
println('ERROR:')
println(cmd2)
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
}
@ -63,10 +55,9 @@ fn main() {
mut out := ''
mut rc := 0
// the following does not work, not sure why not
// out,rc = exec("find /tmp/ && echo '******'")
// find files from /tmp excluding files unlistable by current user
out, rc = exec("find /tmp/ ; echo '******'")
out, rc = exec("find /tmp/ -user \$UID; echo '******'")
println(out)
assert out.ends_with('******\n')