如何prevent FGETS块时,文件流没有新数据 [英] how to prevent fgets blocks when file stream has no new data

查看:140
本文介绍了如何prevent FGETS块时,文件流没有新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有执行尾-f sometextfile一个的popen()函数。 Aslong因为有数据的FILESTREAM显然我可以打通与fgets数据()。现在,如果没有新的数据来自于尾部,与fgets()挂起。我试图ferror()函数和的feof()无济于事。我怎样才能确保与fgets()不尝试读取数据时,没有什么新的文件流吗?

I have a popen() function which executes "tail -f sometextfile". Aslong as there is data in the filestream obviously i can get the data through fgets(). Now, if no new data comes from tail, fgets() hangs. I tried ferror() and feof() to no avail. How can i make sure fgets() doesn't try to read data when nothing new is in the file stream?

其中的建议之一是选择()。由于这是针对Windows平台的选择似乎并没有因为工作的匿名管道似乎并没有为它工作(见的这个帖子)。

One of the suggestion was select(). Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see this post).

推荐答案

在Linux操作系统(或者任何Unix-Y OS),您可以标记()由popen这所使用的底层的文件描述符是不可阻挡。

In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking.

#include <fcntl.h>

FILE *proc = popen("tail -f /tmp/test.txt", "r");
int fd = fileno(proc);

int flags;
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);

如果没有输入可用,与fgets将返回NULL,并将errno设置为EWOULDBLOCK。

If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK.

这篇关于如何prevent FGETS块时,文件流没有新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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