0

对于我的程序,我有一个通过管道连接的主文件和一个帮助文件。主文件通过标准输入写入辅助文件,辅助文件通过标准输出写入主文件。helper 文件是通过 fork 到 main 的子进程,然后运行 ​​exec。当管道从标准输入读取时,如何让辅助方法检查管道是否关闭?目前我正在使用下面的代码,但它只是处于无限循环中,因为标准输入的 EOF 是 ctrl-D,这永远不会发生,因为主函数只发送数据字符串(主要是整数)。

while (1) {
                read(0, buffer, 20 );
                sscanf(buffer, "%d" , &info.numAgents);
                if (feof(stdin)) {
                        fprintf(stdout, "Handler communication breakdown.\n");
                        exit(4);
                }


        }
4

1 回答 1

1

从 pipe(7) 手册页:

   If all file descriptors referring to the write end of a pipe have
   been closed, then an attempt to read(2) from the pipe will see end-
   of-file (read(2) will return 0). 

检查您的读取返回码。

于 2013-09-26T13:51:05.097 回答