我有一个popen()函数执行"tail -f sometextfile".只要文件流中有数据显然我可以通过fgets()获取数据.现在,如果没有来自尾部的新数据,fgets()会挂起.我试过ferror()和feof()无济于事.如何在文件流中没有新内容的情况下确保fgets()不会尝试读取数据?
其中一个建议是select().由于这是针对Windows平台选择似乎不起作用,因为匿名管道似乎不起作用(请参阅此文章).
看看下面的代码:
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
main() {
int pipdes[2];
char buff[50];
const char parent[]="Parent Writes. Child Reads\n";
const char child[]="Child Writes. Parent Reads\n";
if(pipe(pipdes)==0) {
pid_t pid=fork();
if(pid<0)
printf("Error\n");
if(pid==0){
read(pipdes[0],buff,50);
printf("Parent: %s",buff);
write(pipdes[1], child, strlen(child));
exit(0);
}
else if(pid>0) {
write(pipdes[1], parent, strlen(parent));
wait(pid);
read(pipdes[0], buff, 50);
printf("Child: %s", buff);
}
}
else
printf("Error in pipe\n");
}
Run Code Online (Sandbox Code Playgroud)
现在,我在这里创建了一个管道,但这两个进程都可以读写.管道不应该是单向的.此外,当我把传统的'close(pipdes [0])'用于父级和'close(pipdes [1])'用于子级时,代码不起作用,尽管我添加了open(pipdes [0])函数后来.
我对UNIX和管道的概念仍然是原始的,所以我可能在这里有点蹩脚,但请你协助.