How do I get the output of a program ran by exec(). Let's say I have this code:
int main(int argc, char ** argv) {
int fid = fork();
if(fid == 0) {
execlp("ls", "ls", NULL);
}
wait();
return 0;
}
How can the parent process get the output of the ls command?
CodePudding user response:
The exec
family of functions completely replaces the current process. However, they do not close file descriptors unless they marked close-on-exec. Thus, the typical way to do this is to create a pipe where the read side belongs to the parent and the write side belongs to the child.
This would look something like this (error checking omitted and obviously inefficient):
#include <stdint.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char ** argv) {
int pipefd[2];
int status;
uint8_t buf[256];
pipe(pipefd);
int fid = fork();
if(fid == 0) {
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
execlp("ls", "ls", NULL);
}
close(pipefd[1]);
while (read(pipefd[0], buf, 1) > 0)
write(1, buf, 1);
wait(&status);
return 0;
}
Note that to attach the pipe file descriptor to standard output (FD 1), you need to use dup2
. You also need to close the ends of the pipe you're not using, or you may never end up reaching end of file.
If you're interested in the exit status, wait
(or waitpid
) will provide that for you; see the manual page for how to determine if it exited normally and if so, what that status was.