inotify_event 名称在 c++ 中为空

问题描述 投票:0回答:0

我正在 Ubuntu 22.04 上使用 inotify 开发一个 C++ 项目。对于如下所示的简单 inotify 代码:

int wd, fd = inotify_init();
    /* (0) Init inotify */
    if (fd < 0)
    {
        printf("Unable to inizialize inotify()");
        return;
    }
    wd = inotify_add_watch(fd, "/home/chao/Desktop/new_dir/", IN_MODIFY | IN_CREATE | IN_DELETE);
    if(wd < 0)
    {
        perror("");
        return;
    }
    while (1)
    {
        char buffer[EVENT_BUF_LEN];
        int i, length = read(fd, buffer, EVENT_BUF_LEN);
        if (length < 0)
        {
            printf("Iwatch error");
            continue;
        }
        else
            i = 0;
        while (i < length)
        {
            struct inotify_event *event = (struct inotify_event *)malloc(EVENT_SIZE);
            memset(event, 0, EVENT_SIZE);
            memcpy(event, &buffer[i], EVENT_SIZE);
            if (event->len)
            {
                if (event->mask & IN_ISDIR)
                {
                    printf("Directory %s created/moved", event->name);
                    /* Nothing to do */
                }
                else
                {
                    printf("File %s is created/moved", event->name);
                    // handle files...
                }
            }
            i += EVENT_SIZE + event->len;
        }
    }
    inotify_rm_watch(fd, wd);
    close(fd);

我的 ubuntu 上的这段代码在 c++ 文件中使用并用 g++(11.3) 编译时,

printf("File %s is created/moved", event->name);
不打印任何东西! 相反,在 c 文件中并使用 gcc (11.3) 进行编译时,当我在 /home/chao/Desktop/new_dir/ 下创建新文件 f_01 时,我可以正确地得到“文件 f_01 已创建/移动”。

任何人都可以帮助我理解这一点?谢谢!

c++ ubuntu inotify
© www.soinside.com 2019 - 2024. All rights reserved.