【问题标题】:Check an exec is writing to stdin or not in C检查 exec 是否在 C 中写入标准输入
【发布时间】:2013-09-26 21:51:05
【问题描述】:

对于我的程序,我有一个主文件和一个帮助文件,通过管道连接。主文件通过标准输入写入辅助文件,辅助文件通过标准输出写入主文件。 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);
                }


        }

【问题讨论】:

  • 请显示设置管道的代码。您似乎从错误的流中读取数据。

标签: c stdin eof


【解决方案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). 

检查您的读取返回码。

【讨论】:

  • 哦,所以如果我修改我的代码就像: If (read(0, buffer, 20) == 0) { exit stuff { ?
  • 是的,这应该可以工作,除非您的管道设置有问题。
猜你喜欢
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2015-10-02
  • 2019-11-15
  • 1970-01-01
  • 2018-02-21
  • 2012-04-25
  • 2012-02-03
相关资源
最近更新 更多