• 为什么没有进入循环?(一个pipe例子)


    一、有错误的程序代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>
    
    void writer(const char * message, int count, FILE * stream)
    {
        printf("enter writer, count %d\n", count);
        while ( count > 0 )
        {
            fprintf(stream, "%s", message);
            fflush(stream);
            sleep(1);
            count --;
        }
    }
    
    void reader(FILE * stream)
    {
        char buf[256] = {0};
        printf("enter reader\n");
        while ( 0 != feof(stream) && 0 != ferror(stream) && buf == fgets(buf, sizeof(buf), stream) )
        {
            fputs(buf, stdout);
        }
    }
    
    int main(int argc, char ** argv)
    {
        int fds[2];
        FILE * stream;
        pid_t pid;
    
        if ( 0 != pipe(fds) )  
        {//fds[0] for read, fds[1] for write
            printf("create pipe failed.\n");
        }
    
        pid = fork();
        if ( 0 == pid )
        {//child
            printf("子进程 %d\n", getpid());
        
            close(fds[1]);
            stream = fdopen(fds[0], "r");
            reader(stream);
            close(fds[0]);
        }
        else
        {
            printf("父进程 %d\n", getpid());
    
            close(fds[0]);
            stream = fdopen(fds[1], "w");
            writer("hello\n", 5, stream);
            close(fds[1]);
        }
    
        return 0;
    }
    这段程序代码运行结果如下:

    $ gcc pipe.c 
    $ ./a.out 
    子进程 19299
    enter reader
    父进程 19298
    enter writer, count 5

    运行结果显然与期望不符,使用gdb调试,发现程序受到了SIGPIPE信号,然后退出了。

    SIGPIPE是在“reader中止之后写Pipe的时候发送”产生的。SIGPIPE的默认处理时程序退出,好像也没有任何提示。

    最后发现是因为reader中循环条件错了,导致子进程立即退出了,也就关闭了reader端(因为父进程立即关闭了reader端,子进程再关闭一次,reader就没有了)。

    二、修正代码

    将reader方法中的循环条件修改为:

    while ( 0 == feof(stream) && 0 == ferror(stream) && buf == fgets(buf, sizeof(buf), stream) )
    问题解决,运行结果为:

    $ gcc pipe.c 
    $ ./a.out 
    子进程 19329
    enter reader
    父进程 19328
    enter writer, count 5
    hello
    hello
    hello
    hello
    hello
    结果符合期望。

    三、feof和ferror的返回值意义

    当文件读取到末尾时,feof返回非0值,否则返回0.

           当文件读写过程中出错时,ferror返回非0值,否则返回0.

          

  • 相关阅读:
    数组和字符串//反转字符串
    数组和字符串//实现strStr()
    数组和字符串//二进制求和
    数组和字符串//加一
    数组和字符串//至少是其他数字两倍的最大数
    LeetCode111_求二叉树最小深度(二叉树问题)
    数据结构6.8_树的计数
    数据结构6.7_回溯法和树的遍历
    数据结构6.6_赫夫曼树及其应用
    数据结构6.5_树与等价问题
  • 原文地址:https://www.cnblogs.com/yeta/p/3616730.html
Copyright © 2020-2023  润新知