【发布时间】:2016-12-21 22:45:21
【问题描述】:
我有一个守护进程,我需要在其中 fork()/exec() 一些新进程,然后读取子进程 stdout/stderr。
我的问题是父进程是一个守护进程,其中 stdout 和 stderr 已关闭。有没有办法做到这一点?我必须打开一个外壳吗?
int status;
pipe(pipefd_stdout);
pipe(pipefd_stderr);
pid_t pid = fork();
if (pid == 0)
{
close(pipefd_stdout[0]); // close reading end in the child
close(pipefd_stderr[0]); // close reading end in the child
dup2(pipefd_stdout[1], 1); // send stdout to the pipe
dup2(pipefd_stderr[1], 2); // send stderr to the pipe
execvpe(cmd, (char**)args, (char**)env);
}
else
{
// parent ...
waitpid(pid, &status, 0);
close(pipefd_stderr[1]);
close(pipefd_stdout[1]);
}
【问题讨论】:
-
“我必须打开一个 shell 吗?” 不需要,而是建立一个管道。
-
我也有类似的问题。不幸的是,我不能按照您的建议使用管道,因为我正在使用
system()函数。将stdout重定向到临时文件是否正确?