popen() is a posix api to implement single direction communication between two processes. It is suitable for the following conditions: 1. create a subprocess and read its standard output. 2. create a subprocess and write to its standard input.
I think it is something between system() and pipe() plus fork/exec. With system(), you can only start a child process and wait for the termination of child process. With pipe/fork/exec, as it is a little complex, I will show the typical usage below:
MainProcessFn() {
int pipe_fd[2];
pipe(pipe_fd);
int pid = fork();
if (pid == 0) {
close(pipe_fd[0]); // close read side
dup2(pipe_fd[1], 1); // dup to stdout
close(pipe_fd[1]);
exec("some command");
} else {
close(pipe_fd[1]) // close write side
FILE *fp = fdopen(pipe_fd[0], "r");
// read from child process's standard output.
}
}
As we can see, we can do bidirectional communication between two processes with pipe. We can only do unidirectional communication with popen, while the benefit is simpler code.
MainProcessFn() {
FILE* fp = popen("some command", "r");
// read from child process's standard output.
pclose(fp);
}
With pclose, we can wait for the termination of child process, and get the exit status. In fact, popen/pclose is just a library api implemented based on system calls like pipe/fork/exec/waitpid, but just more convenient to use.
No comments:
Post a Comment