我正在學習 fork 和 pipe,但有以下問題:我的目標是構建一個包含 3 個行程的程式,我做到了,但我的問題是:為什么printf("Sum of first half: %d\n", sum);要執行兩次?
我檢查了代碼是否有任何邏輯錯誤,但找不到任何內容。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(int);
int sum;
int fd[2];
pipe(fd);
int id = fork();
if (id == 0) // Child process
{
for (int i = 0; i < size / 2; i )
sum = sum arr[i];
int j = fork();
if (j == 0)
{
printf("Hello I'm the grandchild\n");
}
}
else // Parent process
{
for (int i = size / 2; i < size; i )
sum = sum arr[i];
}
if (id == 0) // Child process writing to the pipe
{
close(fd[0]);
write(fd[1], &sum, sizeof(sum));
close(fd[0]);
printf("Sum of first half: %d\n", sum);
}
else // Parent process reading from the pipe
{
int x;
close(fd[1]);
read(fd[0], &x, sizeof(sum));
close(fd[1]);
printf("Sum of second half: %d\n", sum);
printf("Total sum: %d\n", x sum);
}
}
uj5u.com熱心網友回復:
您的代碼簡化:
int main()
{
int id = fork();
if (id == 0)
fork();
if (id == 0)
printf("Sum of first half\n");
else
printf("Sum of second half\n");
}
和解釋:
| 代碼 | 家長 | 孩子 | 孫子 |
|---|---|---|---|
fork() |
fork |
不適用 | 不適用 |
id 價值 |
id != 0 |
id==0 |
不適用 |
if (id == 0) fork() |
然后沒有執行 | fork |
不適用 |
id 價值 |
id != 0 |
id == 0 |
id == 0 |
if (id == 0) printf("sum first") |
然后沒有執行 | printf |
printf |
else printf("sum second half") |
printf |
否則不執行 | 否則不執行 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327465.html
