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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值