从管道读取后进程退出

Process exits upon reading from pipe

我有一个管道、一个 parent 和一个 child 进程。 parent 从文件中读取一些数据,将其放入管道,然后 child 应该读取所​​有数据。我的问题是这样的:我的parent读取数据,child从管道接收数据,但是当它到达终点时,进程就退出了,退出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个额外的空行

如果该文件描述符还有其他写入程序,则读取块。当您确实关闭了父进程的文件描述符时,子进程的文件描述符仍然打开,并且只会在读取 return 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;
} 

另外,只有你的主进程在退出,子进程作为一个孤立的进程继续存在,永远停留在读取的那个调用上。