【问题标题】:Parallel pipe issue when closing in c在c中关闭时出现平行管道问题
【发布时间】:2021-03-18 15:17:16
【问题描述】:

我目前正在做一个项目,我需要创建多个从不同管道读取的 fork,直到管道关闭。 这里的问题是,如果我创建了多个管道,即使我关闭了所有管道的两侧,孩子仍然会被卡在读取状态。

这是我的代码的简化版本,但存在相同问题:

#include <stdlib.h>
#include <unistd.h>

#define NB_PIPES 2

void    read_write_pipe(int pipefd[2]) { //write what goes through is pipe until it closed
    char buf;

    close(pipefd[1]); //close the writing part of the tube
    while (read(pipefd[0], &buf, 1) > 0)
        write(1, &buf, 1);
    close(pipefd[0]);
    _exit(EXIT_SUCCESS);
}

int main(void)
{
    int pipefd[NB_PIPES][2];
    pid_t cpid;

    for (int i = 0; i < NB_PIPES; i++) { //I create my pype
        pipe(pipefd[i]);
    }
    for (int i = 0; i < NB_PIPES; i++) {
        cpid = fork();
        if (cpid == 0)
            read_write_pipe(pipefd[i]); //create fork who will read from pipe i
        else {
            close(pipefd[i][0]); //close the reading part of pipe i
        }
    }
    for (int i = 0; i < NB_PIPES; i++) {
        write(pipefd[i][1], "Salut\n", 6); //write through pipe i
        close(pipefd[i][1]); //close the writing part of pipe i
    }
    for (int i = 0; i < NB_PIPES; i++) {
        wait(NULL);
    }
    return (0);
}

我用ggc编译

感谢您的阅读和帮助!

【问题讨论】:

  • 当你先创建所有管道然后循环调用fork时,所有进程中的所有管道都会打开,所以你必须关闭所有子进程中所有不相关的管道。
  • 好的!非常感谢你 !它现在有效!我应该重新发布正确的代码以显示答案吗?
  • 您可以为自己的问题添加答案。 (不要修改问题来回答它。)

标签: c pipe fork


【解决方案1】:

感谢 Bodo,我找到了问题所在 这是代码的正确版本:

#include <stdlib.h>
#include <unistd.h>

#define NB_PIPES 2

void    read_write_pipe(int pipefd[NB_PIPES][2], int i) { //write what goes through is pipe until it closed
    char buf;

    for (int j = 0; j < NB_PIPES; j++) {
        if (j != i) {
            close(pipefd[j][0]); //close all the other pipe
            close(pipefd[j][1]);
        }
    }
    close(pipefd[i][1]); //close the writing part of the tube
    while (read(pipefd[i][0], &buf, 1) > 0)
        write(1, &buf, 1);
    close(pipefd[i][0]);
    _exit(EXIT_SUCCESS);
}

int main(void)
{
    int pipefd[NB_PIPES][2];
    pid_t cpid;

    for (int i = 0; i < NB_PIPES; i++) { //I create my pype
        pipe(pipefd[i]);
    }
    for (int i = 0; i < NB_PIPES; i++) {
        cpid = fork();
        if (cpid == 0)
            read_write_pipe(pipefd, i); //create fork who will read from pipe i
        else {
            close(pipefd[i][0]); //close the reading part of pipe i
        }
    }
    sleep(1);
    for (int i = 0; i < NB_PIPES; i++) {
        write(pipefd[i][1], "Salut\n", 6); //write through pipe i
        close(pipefd[i][1]); //close the writing part of pipe i
    }
    for (int i = 0; i < NB_PIPES; i++) {
        wait(NULL);
    }
    return (0);
}

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多