c - 从管道读取数据后进程退出

标签 c pipe posix

我有一个管道、一个父进程和一个子进程。父进程从文件中读取一些数据,将其放入管道中,然后子进程应该读取所​​有数据。我的问题是这样的:我的父进程读取数据,子进程从管道接收数据,但是当它到达末尾时,进程就退出了,退出 while 指令后没有输出,这是应该的。

int main(void)
{
    int inputFile, channel[2], PID;
    if(-1 == pipe(channel))
    {
        perror("Eroare");
        return 0;
    }
    if(-1 == (inputFile = open("data.txt", O_RDONLY)))
    {
        perror("Error");
        return 0;
    }
    if(-1 == (PID = fork()))
    {
        perror("Error");
        return 0;
    }
    if(PID != 0)
    {
        char buffer;
        if(-1 == close(channel[0]))
            perror("Error");
        while(1 == read(inputFile, &buffer, 1))
            write(channel[1], &buffer, 1);
        if(-1 == close(channel[1]))
            perror("Error");
    }
    else
    {
        char buffer;
        while(1 == read(channel[0], &buffer, 1))
            printf("%c\n", buffer);
        if(-1 == close(channel[0]))
            perror("Error");
        if(-1 == close(channel[1]))
            perror("Error");
        printf("Should output this");       
    }
    return 0;
} 

我的数据文件包含字符串:ABC,输出为:

A
B
C

+ 2 个额外的空行

最佳答案

如果该文件描述符仍有其他写入者,则读取 block 。虽然您确实关闭了父进程拥有的文件描述符,但子进程的文件描述符仍然打开,并且只有在读取返回 1 以外的值后才会关闭。但是,读取将阻塞,因为子进程本身被视为写入者。

要解决此问题,只需在开始阅读之前移动调用以关闭写入​​端即可,如下所示:

int main(void)
{
    int inputFile, channel[2], PID;
    if(-1 == pipe(channel))
    {
        perror("Eroare");
        return 0;
    }
    if(-1 == (inputFile = open("data.txt", O_RDONLY)))
    {
        perror("Error");
        return 0;
    }
    if(-1 == (PID = fork()))
    {
        perror("Error");
        return 0;
    }
    if(PID != 0)
    {
        char buffer;
        if(-1 == close(channel[0]))
            perror("Error");
        while(1 == read(inputFile, &buffer, 1))
            write(channel[1], &buffer, 1);
        if(-1 == close(channel[1]))
            perror("Error");
    }
    else
    {
        char buffer;
        if(-1 == close(channel[1]))
            perror("Error");
        while(1 == read(channel[0], &buffer, 1))
            printf("%c\n", buffer);
        if(-1 == close(channel[0]))
            perror("Error");
        printf("Should output this");       
    }
    return 0;
} 

此外,只有您的主进程正在退出,子进程作为孤儿进程继续存在,永远停留在读取调用上。

关于c - 从管道读取数据后进程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145935/

相关文章:

c - 当通过管道提供 STDIN 时,getchar() 在 EOF 上循环

用固定值替换非对角线元素

Python 多处理管道不会正确接收 ()

angular - rxjs takeUntil 不执行finalize

c++ - TCPdump 在接收数据包时是否去除任何 header ?

c - reading/dev/urandom 线程安全吗?

c - printf 改变了我的输出

c - C 中指针变量的范围

c - 运行 `Function Pointers` 在运行 `POSIX` 线程内 `C` `Thread Pool`

c - *p 和 (*p)[3] 在函数中有什么区别?