如何检查是否从标准输入中仍然没有阻止打开? [英] How to check if stdin is still opened without blocking?

查看:144
本文介绍了如何检查是否从标准输入中仍然没有阻止打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的程序写在纯C停止执行时,标准输入被关闭。

I need my program written in pure C to stop execution when stdin is closed.

有在程序主循环进行无限期的工作,也没有办法,我可以使用阻塞检查(如 GETC())有(无数据应该到达标准输入 - 它只是保持打开未知时间)

There is indefinite work done in program main cycle, and there is no way I can use blocking checks (like getc()) there (no data is supposed to arrive on stdin - it just stays opened for unknown time).

我打算在实现的inetd,xinetd的或它们​​的类似物托管的网络守护进程的使用描述的功能 - 同时连接保持打开它应该发出在标准输出上的数据并将其正确关闭时完成的工作。现在我的计划是由托管服务打死,因为它不会终止连接后停止。

I intend to use described functionality in realization of network daemon hosted in inetd, xinetd or their analogs - it should emit data on stdout while connection stays opened and correctly finish work when it closes. Now my program is killed by hosting service as it won't stop after connection termination.

我不知道是否 fctntl() O_NONBLOCK 标志适用于标准输入描述符将允许我使用读取非阻塞模式()功能?我应该使用选择()不知何故?

I wonder if fctntl() with O_NONBLOCK flag applied to stdin descriptor would allow me to use read() function in non-blocking mode? Should I use select() somehow?

P.S。该数据是不应该,但可能到达标准输入。非阻塞读出的一种方式woould是这个问题的答案。

P.S. The data is not supposed but might arrive to stdin. A way of non-blocking readout woould be an answer for the question.

推荐答案

选择()不正是你想要的东西:在一个文件描述符信号操作(读,在这种情况下)(文件,插座,不管)不会阻止。

select() does exactly what you want: signal that an operation (read, in this case) on a file descriptor (file, socket, whatever) will not block.

#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;
}

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

You can now check a file descriptor before use, for instance in order to empty the file descriptor:

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

在您的情况下,使用的fileno(标准输入)以得到标准输入的文件描述符:

In your case, use fileno(stdin) to get the file descriptor of stdin:

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

这篇关于如何检查是否从标准输入中仍然没有阻止打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆