#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将每次读取文件都移到文件开头的位置。