Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;编程并获取其进程id(在linux中)?_C++_Linux - Fatal编程技术网

C++ 如何在C++;编程并获取其进程id(在linux中)?

C++ 如何在C++;编程并获取其进程id(在linux中)?,c++,linux,C++,Linux,我尝试了system(),但不知怎的,当辅助程序运行时,我的主程序(执行辅助程序的主程序)挂起 第二个问题是如何在主程序中获取辅助程序的进程id 使用fork创建新进程,然后使用exec在新进程中运行程序。有很多这样的例子。在您想要创建的父进程中 Fork创建一个全新的进程,并将子进程的pid返回给调用进程,将0返回给新的子进程 在子进程中,您可以使用类似的方法来执行所需的辅助程序。 在父进程中,可以使用等待子进程完成 以下是一个简单的示例: #include <iostream>

我尝试了system(),但不知怎的,当辅助程序运行时,我的主程序(执行辅助程序的主程序)挂起


第二个问题是如何在主程序中获取辅助程序的进程id

使用fork创建新进程,然后使用exec在新进程中运行程序。有很多这样的例子。

在您想要创建的父进程中

Fork创建一个全新的进程,并将子进程的
pid
返回给调用进程,将
0
返回给新的子进程

在子进程中,您可以使用类似的方法来执行所需的辅助程序。 在父进程中,可以使用等待子进程完成

以下是一个简单的示例:

#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;
}
#包括
#包括
#包括
#包括
#包括
int main()
{
std::string cmd=“/bin/ls”;//要运行的辅助程序
pid_t pid=fork();//创建子进程
智力状态;
开关(pid)
{
案例1://错误
佩罗尔(“福克”);
出口(1);
案例0://子进程
execl(cmd.c_str(),0,0);//运行命令
perror(“execl”);//除非出现问题,否则execl不会返回
出口(1);
默认值://父进程,pid现在包含子pid
while(-1==waitpid(pid,&status,0));//等待子项完成
如果(!WIFEXITED(状态)| | WEXITSTATUS(状态)!=0)
{
//处理错误

当我尝试做一个fork()时,我得到了以下错误当我做一个fork()时,它给我一个致命的IO错误11(资源暂时不可用),有时它(成功)或(没有这样的文件或目录)读取,我认为这应该是
如果(!WIFEXITED(status)&&&&
?因为
!WIFEXITED(status)
在您等待孩子完成后总是正确的。@Jeroen我相信它可能是
WIFSIGNALED
?如果(WIFSIGNALED(status)| | WEXITSTATUS(status)!=0),也许使用
会更可读。