【发布时间】:2019-03-14 19:24:12
【问题描述】:
我正在尝试使用 C++ 中的 fork() 创建具有多个子进程的父进程。我尝试使用this question 中的代码创建一个简单的程序,让每个进程向上计数;父母会打印“我是进程 0”,第一个孩子会打印“我是进程 1”,依此类推。
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include <sys/wait.h>
using namespace std;
const int PROCESSES = 5;
void Printer(int psno);
int iAmProcess = 0;
int main()
{
int pids[PROCESSES];
Printer(iAmProcess);
for (int j = 0; j < PROCESSES; j++)
{
if (pids[j] = fork() < 0)
{
perror("Error in forking.\n");
exit(EXIT_FAILURE);
}
else if (pids[j] == 0)
{
Printer(iAmProcess);
exit(0);
}
}
int status;
int pid;
int n = PROCESSES;
while (n > 0)
{
pid= wait(&status);
--n;
}
return 0;
}
void Printer(int psno)
{
printf("I am process %d\n", psno);
}
而不是预期的输出:
I am process 0
I am process 1
I am process 2
I am process 3
I am process 4
I am process 5
我明白了:
I am process 0
I am process 0
I am process 0
I am process 0
然后程序终止。我做错了什么?
【问题讨论】:
-
你在哪里将 IamProcess 更新为 != 0,我没看到
-
我添加了一行“iAmProcess = j+1;”到for循环。但是,它现在只返回 4 次“I am process 1”而不是预期的输出。