Reputation: 1
I have code in python which I modify the stdin and stderr, it work succesfuly but at the end of the program it asks for input (for the shell) python code:
import os
import subprocess
stdin_read, stdin_write = os.pipe()
stderr_read, stderr_write = os.pipe()
os.write(stdin_write, b'\x00\x0a\x00\xff')
os.write(stderr_write, b'\x00\x0a\x02\xff')
subprocess.Popen(["./prog"],stdin=stdin_read, stderr=stderr_read)
code in c (prog.c)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char buf[4];
read(0, buf, 4);
if(!memcmp(buf, "\x00\x0a\x00\xff", 4)){
printf("success -A \n");
}
read(2, buf, 4);
if(!memcmp(buf, "\x00\x0a\x02\xff", 4)){
printf("success -B \n");
}
return 0;
}
I typed theecho "hello world"
I was expecting the program to end and not let me write input to the shell. Do I need to close the pipe I created? What should I do so that this won`t happen to me?
Upvotes: 0
Views: 359
Reputation: 58848
Notice the Python program ended before printing success -A
and success -B
. Apparently ./prog
started, then Python ended, then ./prog
printed its thing. The pipe still exists until all programs that have access to it close it (or end) so ./prog
can still read the data from both pipes.
You typed the echo
command into the shell prompt after python
ended. It's still the same prompt even though ./prog
printed two lines in the middle, between the prompt and your command.
If you want Python to wait for ./prog
to finish you can do that:
my_proc = subprocess.Popen(["./prog"],stdin=stdin_read, stderr=stderr_read)
my_proc.wait()
Upvotes: 1