[英]Forked 10 child processes, how can the parent process collect their return values?
我必須在具有10個子進程的1000個數字的數組中找到最大值(這樣,每個子進程僅檢查一百個值),而父進程只需要收集數據即可。 我已經完成了全部工作,但是我仍然無法讀取值。
這是代碼:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int array[1000];
int i, j;
int pids[10];
int searchminindex;
int searchmaxindex;
int maxindex;
srand(time(NULL));
//fill up array with random numbers
for(i = 0; i < 1000; i++)
{
tomb[i] = random() % 5000;
}
//create 10 child processes
for (i = 0; i < 10; i++) {
if ((pids[i] = fork()) < 0) {
perror("fork");
abort();
}
else if (pids[i] == 0) {
searchminindex = i * 100;
searchmaxindex = (i+1) * 100;
//finding the biggest value
maxindex = searchminindex;
for(j = searchminindex+1; j < maxindex; j++) {
if( array[maxindex] < array[j])
maxindex = j;
}
}
}
for(i = 0; i < 10; i++){
//here's where I'd read the return values of the subarrays
}
return 0;
}
我曾經嘗試過使用管道以及WEXITSTATUS,但我真的很困惑,不知道在哪里封閉管道的一端以及類似的東西,而WEXITSTATUS令我完全迷失了。
有什么可以幫助的嗎?
您需要測試從fork返回的pid,並分支代碼,這樣您的主進程就不會像子進程那樣工作,從而使子進程不會生成自己的子進程。 一旦照顧好...
派生進程之間共享內存被很好地解釋這里
我將使用mmap
在進程之間創建共享內存,您需要為每個進程指定將結果放在何處,然后使用wait
確定何時所有子級都退出了,一個好的程序將評估退出狀態並通知用戶,如果有任何孩子異常退出。
不要忘記在父級退出之前清理共享內存。
您需要測試從fork返回的pid,並分支代碼,這樣您的主進程就不會像子進程那樣工作,從而使子進程不會生成自己的子進程。 一旦照顧好...
mmap或完全設置共享內存的替代方法是使用WEXITSTATUS。 根據手冊頁,它將僅返回最低有效的8位,因此,如果您的返回值可以大於127,則這可能不是您的最佳選擇。 最多可以使用255,但是要注意char的簽名,這不是標准的。
int returned_values[10];
for(int i = 0; i < 10; ++i)
{
int status;
wait(&status);
if(WIFEXITED(status))
returned_values[i] = WEXITSTATUS(status);
else {
//Do something more meaningful here
//This means a child received a signal, or any of the other ways wait returns other than a child exiting.
--i;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.