對於n = 10
輸入,我得到一個奇怪的輸出:創建兩個子進程結束的奇總和,甚至系列
pid = 31456
Sum of Odd series : 25
pid = 31456
Sum of Even series : 30
pid = 31456
代碼
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t child_pid;
int i, j, k, n;
int sum;
//printf("Enter the last number of series : ");
scanf("%d", &n);
printf("pid = %d\n", getpid());
for(i = 0; i < 2; i++)
{
child_pid = fork();
if (child_pid < 0)
{
printf("Failed to create child process . . .");
return 1;
}
else if (child_pid == 0)
{
if (i == 0) //find the sum of odd series
{
sum = 0;
for(j = 1; j <= n; j += 2)
sum += j;
printf("Sum of Odd series : %d\n", sum);
exit(0);
}
else if (i == 1) //find the sum of even series
{
sum = 0;
for(j = 2; j <= n; j += 2)
sum += j;
printf("Sum of Even series : %d\n", sum);
exit(0);
}
}
else
{
wait(&child_pid);
}
}
return 0;
}
Ideone鏈接:ideone.com/TyIkJa
當您使用'fork'時,父進程中的所有數據都被_copied_引入到子進程中:當您在子進程中寫入'sum'時,它不會被傳播回父進程的sum中,如每個子進程將使用它自己的這個變量的版本。 – Nbr44
eww,那麼處理這些問題的正確方法是什麼? –
fork產生了一個過程的副本,所以一旦你退出了孩子,孩子們就會隨着計算出來的數值一起死亡,這些數值是他們本地的。如果你想讀取兒童的值,你必須使用管道或共享內存。 – 2013-11-22 09:02:55