我試圖在C.處理器農場我先開口消息隊列,事後儘量使工作進程:(注意NROF_WORKERS 5)只有1名兒童在5個叉(C)
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。所以我的問題:是對其他進程產生的?如果是這樣,他們怎麼不報告?如果不是,我做錯了什麼?另外,家長根本沒有報告,這是如何引起的?