I am trying to clone the stdout of a process into my program with dup2, and it works, except when I duplicate stdin I can not get it back to its original state again.
My code is as follows.
from os import fork, wait, pipe, execvp, dup2, close
from sys import stdin
def get_input(data):
r,w = pipe()
pid = fork()
old = 0
if pid > 0:
wait()
close(w)
old = dup2(r,0)
for line in stdin:
print('data - ', line.strip())
else:
close(r)
dup2(w,1)
execvp(data.split()[0],data.split())
while True:
get_input(input())
I get and EOFError on the second iteration in the while loop because the stdin still is the pipe.
I tried closing the pipe channel and I tried "rebuilding" the filedescriptor by getting the old_fd but it doesnt change that I get the error.
So after a while i realized that there was no reason to duplicate the file descriptor to stdin, because I don't need to pass any data out of the process.
So I could just use the systemcall
read
which will read the byes of the file descriptor given to it.Fist I imported
read
fromos
:and then I deleted everything in the parent process and added the following:
And now I have all the output of stdout captured as a string inside my python program.