从管道读取时进程退出

时间:2017-05-23 22:17:23

标签: 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个额外的空行

1 个答案:

答案 0 :(得分:1)

如果该文件描述符还有其他编写器,则读取块。当你关闭了父文件的文件描述符时,子文件的文件描述符仍然是打开的,只有在读取后返回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;
} 

此外,只有你的主要流程正在退出,孩子仍然是孤儿过程,永远停留在那个阅读的电话上。

相关问题