如何使用轮询linux函数调用使用静态文件描述符?
轮询正在无限时间间隔内运行。 我想在文件中写入某些内容或更新文件时点击轮询。 但poll无法检测文件何时写入如何使用轮询linux函数调用使用静态文件描述符?,linux,file-io,polling,Linux,File Io,Polling,轮询正在无限时间间隔内运行。 我想在文件中写入某些内容或更新文件时点击轮询。 但poll无法检测文件何时写入 #include <stdio.h> #include <poll.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <sys/types
#include <stdio.h>
#include <poll.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
char buf[5]="true";
struct pollfd ufds[1];
int rv;
ufds[0].fd = 0;
ufds[0].events = POLLIN;
char *filename="textfile.txt";
ssize_t ret_write,ret_read;
ufds[0].fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 5);
if(ufds[0].fd== -1){
perror("open");
return 3;
}
while(1) {
ret_write= write (ufds[0].fd, &buf, (ssize_t) 5);
if((rv = poll(ufds, 1,-1 )) == -1) perror("select");
else if (rv == 0) printf("Timeout occurred!\n");
else if (ufds[0].revents & POLLIN) {
printf("return hit\n");
read(ufds[0].fd, buf, 5);
}
fflush(stdout);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main(){
char buf[5]=“真”;
结构pollfd ufds[1];
int-rv;
ufds[0].fd=0;
ufds[0]。事件=POLLIN;
char*filename=“textfile.txt”;
再写再读;
ufds[0].fd=open(文件名,O_WRONLY | O|u CREAT | O|u TRUNC,5);
if(ufds[0].fd==-1){
佩罗(“公开”);
返回3;
}
而(1){
ret_write=write(ufds[0].fd,&buf,(ssize_t)5);
如果((rv=轮询(ufds,1,-1))==-1)或(“选择”);
如果(rv==0)printf(“发生超时!\n”);
else if(ufds[0]。revents和POLLIN){
printf(“返回命中\n”);
读取(ufds[0].fd,buf,5);
}
fflush(stdout);
}
返回0;
}
您的示例无法运行,因为该文件未打开以供读取。即使打开文件进行读取,代码也不会按预期工作,因为轮询将在文件末尾成功返回
您需要的是inotify函数。请先自己试一试,当您的代码无法正常工作时,请提出一个问题。您不能为此使用
poll
。使用inotify
,您可能会更走运。您能否举例说明如何操作。我尝试使用inotify,但它仅适用于目录,不适用于指定的文件。我还希望inotify永远工作,而不使用while(1){}之类的循环语句,以避免线程继续运行。您能推荐任何只在文件上连续工作而不使用while的函数吗。