how to prevent fgets blocks when file stream has no new data

岁酱吖の 提交于 2019-11-27 09:26:56
DGentry

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);

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

fgets() is a blocking read, it is supposed to wait until data is available if there is no data.

You'll want to perform asynchronous I/O using select(), poll(), or epoll(). And then perform a read from the file descriptor when there is data available.

These functions use the file descriptor of the FILE* handle, retrieved by: int fd = fileno(f);

i solved my problems by using threads , specifically _beginthread , _beginthreadex.

You can instead try reading sometextfile using low-level IO functions (open(), read(), etc.), like tail itself does. When there's nothing more to read, read() returns zero, but will still try to read more the next time, unlike FILE* functions.

I you would use POSIX functions for IO instead of those of C library, you could use select or poll.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!