【发布时间】:2017-01-23 13:16:43
【问题描述】:
我正在尝试在 C 中创建一个处理器场。我从打开消息队列开始,然后尝试创建工作进程:(注意 NROF_WORKERS 为 5)
static void
makechildren (void) {
// Only the parent should fork. Any children created will become workers.
pid_t processID;
pid_t farmerPID = getpid(); // To identify who the farmer is
// Loop creating processes, indexed by NROF_WORKERS
int i = 0;
while (i < NROF_WORKERS){
if (getpid() == farmerPID){
i++;
printf ("Parent is creating a child!%d\n", getpid());
processID = fork();
}
}
if (processID < 0){
perror("fork() failed");
exit(1);
}
else {
// If parent, start farming
if (processID == farmerPID) {
printf("Parent reporting in!%d\n");
}
// If child, become a worker
if (processID == 0) {
printf("Child reporting in!%d\n", getpid());
join();
}
}
}
如您所见,我希望父母在任何时候创建孩子时报告,然后我希望父母和所有孩子都报告。然而,这就是我得到的全部:
Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Parent is creating a child!11909
Child reporting in!11914
现在,我确实注意到 11909 和 11914 的差异是 5。所以我的问题是:是否创建了其他进程?如果是这样,他们为什么不报告?如果没有,我做错了什么?还有,家长根本不报,这是怎么造成的?
【问题讨论】: