gpt4 book ai didi

在 C 中检查 exec 是否正在写入 stdin

转载 作者:行者123 更新时间:2023-11-30 15:45:28 25 4
gpt4 key购买 nike

对于我的程序,我有一个主文件和一个辅助文件,通过管道连接。主文件通过 stdin 写入辅助文件,辅助文件通过 stdout 写入主文件。辅助文件是通过 fork 到主进程的子进程,然后运行 ​​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);
}


}

最佳答案

来自 pipeline(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).

检查您读取的返回代码。

关于在 C 中检查 exec 是否正在写入 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19030103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com