【问题标题】:Does the following code runs two child process executing in parallel from a single parent process in C++?以下代码是否从 C++ 中的单个父进程并行运行两个子进程?
【发布时间】:2015-01-05 21:00:19
【问题描述】:

我已经读到 fork 可用于运行两个子进程,从 C++ 中的单个父进程并行执行,如 How to create two child process executing parallel from a single parent process in C++? 中所述;但是,没有示例可以创建我自己的实验。因此,我使用了以下代码,但我不确定这两个进程是否并行执行。此外,由于任务是从两个设备捕获数据,因此需要在不同的终端中运行它们,我唯一想到的就是使用以下行:

system("xterm -e ./task1"); 

然而,一旦它执行了下面的输出 sh: 1: term: not found

 如果您能提供任何建议或指导,我们将不胜感激

#include <iostream>
#include <stdlib.h> 
using namespace std;

int main(int argc, char **argv)
{

  cout << "--beginning of program" << endl;
    int counter = 0;
    pid_t pid = fork();

    if (pid == 0)
    {
        // child process
        system("./task1");
cout << "child process" << endl;
    }
    else if (pid > 0)
    {
        // parent process
                system("./task2");
cout << "parent process" << endl;
    }
    else
    {
cout << "fork() failed!\n" << endl;
        return 1;
    }
    cout << "--end of the program" << endl;
    return 0;
}

【问题讨论】:

标签: c++ linux parallel-processing fork


【解决方案1】:

问题标题暗示你认为这段代码创建了两个子进程和一个父进程,总共三个进程,而你的问题正文暗示你认为有一个父进程和一个子进程。我不清楚你到底相信哪一个。

可以肯定的是:此代码将创建一个与父进程并行运行的额外子进程,总共两个进程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2017-06-29
    相关资源
    最近更新 更多