我是 C 语言的新手,今天,我在尝试关闭使用 popen 函数创建的“Open Stream”时遇到了一个问题。1. 这个问题是不是因为我在这个程序中使用了 poll 函数?2.还是因为fcntl功能?如果有人教我这个问题的确切原因,我会很高兴。我附上下面的代码示例,请看一下。
代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
char line[1024];
FILE *tfd;
int readData(int *fd)
{
struct pollfd pfd;
int pollTime = 10000;
pfd.events = POLLIN;
pfd.fd = *fd;
int ret=1;
ret = poll(&pfd,1,pollTime);
printf("\nAfter ret=%d\n.",ret);
if(ret == -1 || ret ==0)
{
printf("Couldn't poll returned : %d\n", ret);
return 0;
} else {
if( fgets(line,sizeof(line),tfd) == NULL )
{
printf("\nReturns nothing.");
return 0;
}
printf("\nRead Some data.");
}
return ret;
}
void main(void)
{
int ret;
int fd, flags;
char filepath[] = "/home/TEST/";
char filename[] = "log.txt";
char cmd[100];
sprintf(cmd,"tail -f %s%s",filepath, filename);
tfd = popen(cmd, "r");
fd = fileno(tfd);
flags = fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
if(tfd==NULL)
{
printf("\npopen failed, exiting.\n");
exit(0);
}
while( (ret=readData(&fd)) > 0 )
{
printf("\nret2=%d.",ret);
printf("\nLine : %s",line);
}
printf("\n**********DONE****************.\n");
pclose(tfd);
}
输出:
[root@localhost TEST]# ./polltail
After ret=1
.
Read Some data.
ret2=1.
Line : 64 bytes from maa03s05-in-f4.1e100.net (74.125.236.68): icmp_req=31 ttl=52 time=38.4 ms
After ret=0
.Couldn't poll returned : 0
**********DONE****************.
在这里,我希望提示出现在执行结束时。但是,它不会到来。