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?
To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.
The way we can redirect the output is by closing the current file descriptor and then reopening it, pointing to the new output. We'll do this using the open and dup2 functions. There are two default outputs in Unix systems, stdout and stderr. stdout is associated with file descriptor 1 and stderr to 2.
Redirecting output to Multiple files and screen: If you want to redirect the screen output to multiple files, the only thing you have to do is add the file names at the end of the tee command.
For sending the output to another file (I'm leaving out error checking to focus on the important details):
if (fork() == 0) { // child int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); dup2(fd, 1); // make stdout go to file dup2(fd, 2); // make stderr go to file - you may choose to not do this // or perhaps send stderr to another file close(fd); // fd no longer needed - the dup'ed handles are sufficient exec(...); }
For sending the output to a pipe so you can then read the output into a buffer:
int pipefd[2]; pipe(pipefd); if (fork() == 0) { close(pipefd[0]); // close reading end in the child dup2(pipefd[1], 1); // send stdout to the pipe dup2(pipefd[1], 2); // send stderr to the pipe close(pipefd[1]); // this descriptor is no longer needed exec(...); } else { // parent char buffer[1024]; close(pipefd[1]); // close the write end of the pipe in the parent while (read(pipefd[0], buffer, sizeof(buffer)) != 0) { } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With