c - UNIX 先进先出 : the process hangs if I don't close the input side of the fifo

标签 c unix fifo

我刚刚开始使用 UNIX FIFO,并且在试验我的第一个 FIFO 程序时发现了一些东西。该程序是这样工作的:创建 FIFO 后,使用 fork() 函数启动两个进程。子进程通过FIFO读取父亲传给他的东西,打印到屏幕上。交换的数据是指定为参数的字符串。问题是:在父部分,如果我忘记关闭 FIFO 的输入端(意味着我排除了 close(fd) 行)程序就会挂起,即使数据介于进程交换正确。否则,一切正常,程序终止而不会挂起。谁能解释一下为什么?

感谢您的耐心等待。这是主要功能的代码:

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("An argument must be specified\n");
        return -1;
    }   

    int ret = mkfifo("./fifo.txt", 0644);
    char buf;

    if(ret < 0)
    {
        perror("Error creating FIFO");
        return -1;
    }

    pid_t pid = fork();

    if(pid < 0)
    {
        perror("Error creating child process");
        return -1;
    }

    if(pid == 0) /* child */
    {
        int fd = open("./fifo.txt", O_RDONLY); /* opens the fifo in reading mode */

        while(read(fd, &buf, 1) > 0)
        {
            write(STDOUT_FILENO, &buf, 1);
        }
        write(STDOUT_FILENO, "\n", 1);
        close(fd);
        return 0;
    }
    else /* father */
    {
        int fd = open("./fifo.txt", O_WRONLY); /* opens the fifo in writing mode */

        write(fd, argv[1], strlen(argv[1]));
        close(fd);
        waitpid(pid, NULL, 0);
        return 0;
    }
}

最佳答案

read(2) 阻塞,直到有可用的字符或 channel 在另一端关闭。父进程必须关闭管道,以便最后一个子进程 read() 返回。如果在父亲中省略 close(fd), child 将阻塞在 read() 中,直到父亲退出(自动关闭管道)但父亲会挂起waitpid() 直到 child 退出。

关于c - UNIX 先进先出 : the process hangs if I don't close the input side of the fifo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669609/

相关文章:

c - 如何搜索字符串并替换文本文件中的字符串?

linux - 如何使 zsh `run-help` 忽略 `sudo` 并获得有关以下命令的帮助

linux - 如何在 zgrep 上使用正则表达式?

linux - 如何在 Linux 中创建一个大小的 FIFO 缓冲区?

c - 为具有空终止字符的 fgets 分配内存字符串

c - 使用 scanf 在 C 中向后打印字符串

带有用户定义换行符的 Unix 排序文本文件

ipc - 使用 System V 信号量时的挑战和奇怪的经历

pipe - F_GETPIPE_SZ 在 C 中返回 -1

c - IAR 使用不同的 #define 构建库