libc system popen, :
int system(cont char *command) {
const char *argv[4] = {"/bin/sh", "-c", command};
int status;
pid_t child = fork();
if (child == 0) {
execve(argv[0], argv, NULL);
exit(-1);
}
waitpid(child, &status, 0);
return status;
}
FILE *popen(const char *command, const char *type) {
int fds[2];
const char *argv[4] = {"/bin/sh", "-c", command};
pipe(fds);
if (fork() == 0) {
close(fds[0]);
dup2(type[0] == 'r' ? 0 : 1, fds[1]);
close(fds[1]);
execve(argv[0], argv, NULL);
exit(-1);
}
close(fds[1]);
return fdopen(fds[0], type);
}
( , )
If you need more subtle control over the processing of arguments (instead of going through sh), or you want to control more than one of them {stdin, stdout, stderr}, you will have to write it yourself or find a library. But the standard library covers most use cases.
source
share