c++ 用poll监听文件内容变化或从命令行获取数据
·
#include <iostream>
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <cmath>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
int ret;
int fd;
struct pollfd fds[2];
char tempp[100] = {0};
fd = open("./data.txt", O_RDONLY);
if(fd < 0) {
perror("open file: ");
return -1;
}
ret = 0;
fds[0].fd = 0;
fds[1].fd = fd;
fds[0].events = POLLIN;
fds[1].events = POLLIN;
while (1) {
ret = poll(fds, 2, -1);
if(ret == -1)
perror("poll(): ");
else if(ret > 0){
char buf[100] = {0};
if((fds[0].revents & POLLIN) == POLLIN) {
read(0, buf, sizeof(buf));
printf("stdin buf = %s\n", buf);
} else if((fds[1].revents & POLLIN) == POLLIN) {
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
if(strcmp(buf, tempp) != 0) {
memcpy(tempp, buf, sizeof(buf));
printf("file buf = %s tempp = %s\n", buf, tempp);
}
} else if(ret == 0)
printf("time out\n");
sleep(1);
}
return 0;
}
测试方法:
通过lseek将每次读取文件都移到文件开头的位置。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)