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?
You need to decide exactly what you want to do - and preferably explain it a bit more clearly.
If you know which file you want the output of the executed command to go to, then:
If you want the parent to read the output from the child, arrange for the child to pipe its output back to the parent.
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 normal fscanf
, fread
etc.
You could also use the linux sh
command and pass it a command that includes the redirection:
string cmd = "/bin/ls > " + filepath;
execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);
After forking, use dup2(2)
to duplicate the file's FD into stdout's FD, then exec.
Source: Stackoverflow.com