I'm writing a C program where I fork()
, exec()
, and wait()
. I'd like to take the output of the program I exec'ed to write it to file or buffer.
For example, if I exec ls
I want to write file1 file2 etc
to buffer/file. I don't think there is a way to read stdout, so does that mean I have to use a pipe? Is there a general procedure here that I haven't been able to find?
After forking, use
dup2(2)
to duplicate the file's FD into stdout's FD, then exec.Since you look like you're going to be using this in a linux/cygwin environment, you want to use popen. It's like opening a file, only you'll get the executing programs
stdout
, so you can use your normalfscanf
,fread
etc.You need to decide exactly what you want to do - and preferably explain it a bit more clearly.
Option 1: File
If you know which file you want the output of the executed command to go to, then:
Option 2: Pipe
If you want the parent to read the output from the child, arrange for the child to pipe its output back to the parent.
For sending the output to another file (I'm leaving out error checking to focus on the important details):
For sending the output to a pipe so you can then read the output into a buffer: