pid_t pid;
pid=fork();
if (pid == 0)
{
//child process.
execl("/opt/bin/version.out", "version.out > /tmp/version",0);
_exit(0);
}
else
{
// this is parent, wait for child to finish.
waitpid(pid, NULL, 0);
verDir("/tmp/version");
}
使用上面的 C++ 代码,我尝试创建一个子进程,执行命令/opt/bin/version.out 并将输出重定向到/tmp/version,但它根本不创建/tmp/version,上述语法有任何错误吗? execl() 和 waitpid() 语法正确吗?谢谢。
最佳答案
“>”重定向在 execl 中无效,因为它是 shell 命令....
尝试查看Running a script from execl()有关如何调用 shell 来执行执行的示例...
如果您想避免 shell 调用,则必须执行“dup”调用来关闭 chiled 进程中的 stderr/stdout 并将其打开到文件中 - 您可以在此处查看示例; fork, pipe exec and dub2
或者在您的子进程中,您可以通过关闭标准输出并将其作为文件重新打开来强制输出到特定文件,如下所示;
if (pid == 0)
{
//child process.
close(1);
creat("/tmp/version",0644); // this will create a new stdout
close(2);
dup(1); // this will make stderr to also go to the same file.....
execl("/opt/bin/version.out", "version.out",0);
perror("execl didn't work"); // print out the error if execl failed...
_exit(0);
}.....
关于linux - 如何在 Linux 中重定向生成的子进程的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23071549/