1
我想了解c中的fork是如何工作的。我試圖解決的問題是;給定f(上),我試圖找到f(1)+ f(2)+ .. f(上)。 我想做多進程編程來讓fork每個子進程並讓每個子進程計算f(x)。因此,f(1),f(2)... f(upper)是由每個子進程計算出來的。創建多於6個子進程的共享內存出錯
父進程應計算以下f(1)+ .. + f(上)。 這裏是我的代碼
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include<sys/shm.h>
#include<sys/ipc.h>
int upper = 0;
int n = 0;
int main(int argc, char*argv[]){
pid_t pid;
if(argc != 2){
printf("Input one argument");
return -1;
}
upper = atoi(argv[1]);
int segment_id;
int *s;
pid_t *pids;
pids = (pid_t *) malloc(sizeof(int) * upper);
s = (int *) malloc(sizeof(int) * upper);
key_t key = 4141;
if((segment_id = shmget(key, upper * sizeof(int), IPC_CREAT | 0667))< 0) perror("shmget: failure");
if((s = shmat(segment_id, NULL, 0)) == (char *) -1){
perror("shmat : failure");
exit(1);
}
for(int i = 1; i <= upper; i++){
pid = fork();
if(pid == 0) {
n = i;
break;
}
pids[i] = pid;
}
if(pid > 0){
wait(1 * upper);
int totalSum;
for(int i = 0; i < upper; i++){
totalSum += s[i];
}
printf("Total sum = %d", totalSum);
} else {
sleep(2);
int sum = 0;
for(int i = 0; i <= n; i++){
sum += i;
}
s[n - 1] = sum;
printf("n => %d : sum %d\n", n, sum);
}
}
但是每當我試圖用參數運行這個程序超過6 我收到無效的參數錯誤。
有什麼想法背後的'等待(1 *上);',好嗎? – alk