使用 fork() 从父进程和子进程计算的总和在 C 中不正确

问题描述 投票:0回答:1

我希望就以下问题获得一些帮助。 因此,在子进程中我得到一个值 7,这证实了 for 循环之后的 printf 语句。 然而问题是,在将子进程的总和值写入父进程中的partial_sum之后,我收到了不同的值32_768。因此最终的结果不等于 13。

有人可以帮我找到代码中的问题吗? 预先感谢!

// question: what is the issue here???

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>

int main (int argc, char* argv[]) {
    int arr[] = {1, 2, 3, 4, 1, 2};
    int arr_size = sizeof(arr) / sizeof(int);
    int start, end;
    int pid = fork();
    int fd[2];
    if (pipe(fd) == -1) return 1;

    if (pid == 0){
        start = 0;
        end = arr_size / 2;
    } else {
        start = arr_size / 2;
        end = arr_size;
    }

    // calculation:
    int sum = 0;
    for (int i = start ; i < end; i++) {
        sum += arr[i];
    }
    printf("The sum is: %d\n", sum);

    // transferring the value;
    if (pid == 0) {
        close(fd[0]);
        if(write(fd[1], &sum, sizeof(sum)) == -1) return 1;
        close(fd[1]);
    } else {
        int partial_sum;
        close(fd[1]);
        if (read(fd[0], &partial_sum, sizeof(partial_sum)) == -1) return 2;
        close(fd[0]);
        int result = partial_sum + sum;
        printf("The final result is: %d", result);
        wait(NULL);
    }


}

原本期望结果为 13,但得到以下输出:

The sum is: 7
The sum is: 6
The final result is: 32774
Process finished with exit code 0
c pipe fork
1个回答
0
投票

当在

pipe
之后调用
fork
时,它会在当前进程中打开一个单独的管道,因此您在父进程中获得一个管道,在子进程中获得另一个管道。

将呼叫移至

pipe
,然后再移至
fork
。这将创建一个管道,当
fork
复制该进程时,该管道将被共享。

© www.soinside.com 2019 - 2024. All rights reserved.