使用fgets作为非阻塞函数c ++ [英] using fgets as non-blocking function c++

查看:4116
本文介绍了使用fgets作为非阻塞函数c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个程序,从stdin中读取一个循环,使用函数fgets,如下:

I'm writing a program that reads in a loop from the stdin, using the function fgets, as follows:

while(fgets(buffer2, BUFFERSIZE , stdin) != NULL){
  //Some code  
}

我想我的代码是非阻塞的,也就是说:当用户没有输入时,我不希望程序保持在'fgets'行。
$

I want my code to be non-blocking, that is: I don't want the program to hold on the 'fgets' line when there's no input at the moment from the user.
How can i do it?

推荐答案

fgets

fgets() is a blocking function, it is meant to wait until data is available.

如果你想执行异步I / O,你可以使用 select() poll() strong> epoll()

If you want to perform asynchronous I/O, you can use select(), poll(), or epoll(). And then perform a read from the file descriptor when there is data available.

这些函数使用FILE *句柄的文件描述符,检索方式为:

These functions use the file descriptor of the FILE* handle, retrieved by:

int fd = fileno(f);

如果您使用的是Unix或Linux,则一个解决方案可以标记文件为非阻塞。示例:

If you are using Unix or Linux, then one solution can be to mark the file descriptor used by the file to be non-blocking. Example:

#include <fcntl.h>  
FILE *handle = popen("tail -f /als/als_test.txt", "r"); 
int fd = fileno(handle);  
flags = fcntl(fd, F_GETFL, 0); 
flags |= O_NONBLOCK; 
fcntl(fd, F_SETFL, flags); 

fgets 将返回null并为您设置错误代码。

fgets should be non-blockng now and will return a null and set an error code for you.

这篇关于使用fgets作为非阻塞函数c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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