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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…