gpt4 book ai didi

c - 如何检查 stdin 是否仍然打开而不阻塞?

转载 作者:太空狗 更新时间:2023-10-29 16:54:07 24 4
gpt4 key购买 nike

我需要用纯 C 编写的程序在 stdin 关闭时停止执行。

程序主循环中有不确定的工作,我无法在那里使用阻塞检查(如 getc())(没有数据应该到达标准输入 - 它只是停留打开时间未知)。

我打算使用描述的功能来实现在 inetd、xinetd 或它们的类似物中托管的网络守护进程——它应该在连接保持打开时在 stdout 上发出数据,并在连接关闭时正确完成工作。现在我的程序被托管服务杀死,因为它不会在连接终止后停止。

我想知道将 O_NONBLOCK 标志应用到 stdin 描述符的 fctntl() 是否允许我在非阻塞中使用 read() 函数模式?我应该以某种方式使用 select() 吗?

附言数据不应该但可能到达标准输入。一种非阻塞读出的方法将是这个问题的答案。

最佳答案

select() 完全按照您的意愿行事:表明对文件描述符(文件、套接字等)的操作(在本例中为读取)不会阻塞。

#include <stdio.h>
#include <sys/select.h>

int is_ready(int fd) {
fd_set fdset;
struct timeval timeout;
int ret;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
timeout.tv_sec = 0;
timeout.tv_usec = 1;
//int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
struct timeval *timeout);
return select(fd+1, &fdset, NULL, NULL, &timeout) == 1 ? 1 : 0;
}

您现在可以在使用前检查文件描述符,例如为了清空文件描述符:

void empty_fd(int fd) {
char buffer[1024];
while (is_ready(fd)) {
read(fd, buffer, sizeof(buffer));
}
}

在你的例子中,使用 fileno(stdin) 获取标准输入的文件描述符:

if (is_ready(fileno(stdin))) {
/* read stuff from stdin will not block */
}

关于c - 如何检查 stdin 是否仍然打开而不阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1594251/

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