【问题标题】:Statement getting executed multiple times when out of child-parent for loop超出子父 for 循环时,语句被多次执行
【发布时间】:2021-03-26 21:03:20
【问题描述】:

如何等待所有分叉的进程终止,然后打印在一个
中计算的最终值 多变的。我有以下c程序。它通过分布数组来计算数组的总和
在使用 fork() 的 10 个不同线程中。但是当我退出创建
的 for 循环时 fork() 并打印一个多次打印的值。

    typedef struct
{
    int start;
    int end;
} range;
int main(int argc, char *argv[])
{
    int a[100];
    int totalSum = 0;
    for (int i = 0; i < 100; i++)
        a[i] = 1;
    int num_processes = 10;
    int pipefd[2 * num_processes][2];
    pid_t cpid;
    char buf;

    for (int i = 0; i < 2 * num_processes; i++)
    {
        if (pipe(pipefd[i]) == -1)
        {
            perror("pipe");
            exit(EXIT_FAILURE);
        }
    }

    for (int i = 0; i < num_processes; i++)
    {
        cpid = fork();

        if (cpid == -1)
        {
            perror("fork");
            exit(EXIT_FAILURE);
        }

        if (cpid == 0)
        {
            /* Child reads from pipe */
            close(pipefd[i][1]); /* Close unused write end */
            range *rangePtr = malloc(sizeof(range));
            int sum = 0;

            while (read(pipefd[i][0], rangePtr, sizeof(range)) > 0)
            {
                int start = rangePtr->start;
                int end = rangePtr->end;
                for (int i = start; i <= end; i++)
                    sum += a[i];
            }

            write(pipefd[num_processes + i][1], &sum, sizeof(sum));
            close(pipefd[i][0]);
            close(pipefd[num_processes + i][1]);
            break;
        }
        else
        { /* Parent writes argv[1] to pipe */
            /* Close unused read end */
            range *rangePtr = malloc(sizeof(range));
            rangePtr->start = i * 10;
            rangePtr->end = i * 10 + 9;
            close(pipefd[i][0]);
            write(pipefd[i][1], rangePtr, sizeof(range));
            close(pipefd[num_processes + i][1]);
            close(pipefd[i][1]); /* Reader will see EOF */
            wait(NULL);          /* Wait for child */
            int sum;
            while (read(pipefd[num_processes + i][0], &sum, sizeof(sum)) > 0)
            {
                totalSum += sum;
            }

            close(pipefd[num_processes + i][0]);
            // write(STDOUT_FILENO, &totalSum, sizeof(totalSum));
        }
    }
    printf("%d\n", totalSum);

    _exit(EXIT_SUCCESS);
}

在上面,我期望在 for 循环之外的 totalSum 变量的值
只打印一次。但我看到了

0
10
20
30
40
50
60
70
80
90
100

作为输出。这可能是什么原因?

【问题讨论】:

    标签: c fork


    【解决方案1】:

    每个子进程都进入if (cpid == 0)语句,其末尾有break;,所以子进程退出循环,循环结束后继续,即继续执行命令printf("%d\n", totalSum);

    如果您不想这样,只需将 break; 替换为 return 0;

    【讨论】:

    • 或者exit(0);_exit(0); 更好,以防您最终将此代码移至子程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多