我试过系统(),但不知何故,当第二个程序运行时,我的主程序(执行辅助程序的主程序)挂起如何在C++程序中启动可执行文件并获取其进程ID(在Linux中)?
第二个问题是我如何获得主程序中的辅助程序的进程ID程序?
我试过系统(),但不知何故,当第二个程序运行时,我的主程序(执行辅助程序的主程序)挂起如何在C++程序中启动可执行文件并获取其进程ID(在Linux中)?
第二个问题是我如何获得主程序中的辅助程序的进程ID程序?
使用fork创建一个新进程,然后exec在新进程中运行一个程序。有很多这样的例子。
在父进程中你想要fork
。
叉子创建一个全新的进程,并将子进程的pid
返回到调用进程,并将0
返回到新的子进程。
在孩子的过程中,你可以使用像execl
这样的东西来执行你想要的辅助程序。 在父进程中,您可以使用waitpid
等待孩子完成。
下面是一个简单的说明性的例子:
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
int main()
{
std::string cmd = "/bin/ls"; // secondary program you want to run
pid_t pid = fork(); // create child process
int status;
switch (pid)
{
case -1: // error
perror("fork");
exit(1);
case 0: // child process
execl(cmd.c_str(), 0, 0); // run the command
perror("execl"); // execl doesn't return unless there is a problem
exit(1);
default: // parent process, pid now contains the child pid
while (-1 == waitpid(pid, &status, 0)); // wait for child to complete
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
{
// handle error
std::cerr << "process " << cmd << " (pid=" << pid << ") failed" << std::endl;
}
break;
}
return 0;
}
我认为这应该是'if(!WIFEXITED(status)&& ....'?因为'!WIFEXITED(status)'在你等待孩子完成之后总是成立。 – Jeroen
@Jeroen我相信它可以是'WIFSIGNALED'?也许它更易于使用if(WIFSIGNALED(status)|| WEXITSTATUS (状态)!= 0)' –
我得到试图做一个fork()的时候我做了fork()的,它给了我一个致命IO错误11时,跟随误差(资源暂时无法获得)在X上,有时它的(成功)或(没有这样的文件或目录) – user1265478
阅读http://advancedlinuxprogramming.com/ –