【发布时间】: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;
}
【问题讨论】:
-
阅读Advanced Linux Programming 它有几个章节来回答你的问题。请注意,system(3) 是
fork-ing 然后execve-ing 是/bin/sh -c进程
标签: c++ linux parallel-processing fork