linux - 如何在 Linux 中重定向生成的子进程的输出?

标签 linux exec

     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/

相关文章:

linux - 如何结合 echo 和查找?

linux - 如何在 bash 中用前导零替换文件名中的数字?

linux - Arch Linux Pacman 监视器

php - 关于 PHP 中的 exec() 函数

python - 如何在 Python 中切换执行到新脚本?

linux - 设置挂起超时跨窗口管理器

linux - 是否可以访问 Jenkins 从机的文件?

php - 从 PHP 调用特定版本的 python

ruby - `exec' : string contains null byte (ArgumentError)

c - execvp 的阻塞版本 (windows)