首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >inotify的非阻塞select

inotify的非阻塞select
EN

Stack Overflow用户
提问于 2016-10-28 03:23:41
回答 2查看 1.3K关注 0票数 1

我试图在线程内的c++中使用inotify,但是select阻塞了,所以当我的应用程序退出时,我永远不能离开线程

如何创建inotify手表

代码语言:javascript
复制
fd=inotify_init1(IN_NONBLOCK);
// checking for error
if ( fd < 0 ) 
    log->Print("Could not init files listener");
else
{
    // use select watch list for non-blocking inotify read
    FD_ZERO( &watch_set );
    FD_SET( fd, &watch_set );

    int flags = fcntl(fd, F_GETFL, 0);
    fcntl(fd, F_SETFL, flags | O_NONBLOCK);

    // watch directory for any activity and report it back to me 
    int wd=inotify_add_watch(fd,folder.c_str(),IN_ALL_EVENTS);

    // add wd and directory name to Watch map
    watch.insert( -1, folder, wd );

    // start listening thread
    run(FilesListener::threadBootstrap);
}

下面是在我的线程循环中调用的函数

代码语言:javascript
复制
void FilesListener::refresh()
{
    char buffer[1024];

    // select waits until inotify has 1 or more events.
    // select needs the highest fd (+1) as the first parameter.
    select( fd+1, &watch_set, NULL, NULL, NULL );

    // Read event(s) from non-blocking inotify fd (non-blocking specified in inotify_init1 above).
    int length = read( fd, buffer, EVENT_BUF_LEN ); 
    if ( length < 0 ) 
        log->Print("Could not read inotify file descriptor");
    else
    {  
    ....
EN

回答 2

Stack Overflow用户

发布于 2017-11-22 04:12:54

查看https://github.com/paulorb/FileMonitor它有一个简单的界面来实现你想要的东西。它是使用inotify将windows API移植到Linux。

示例:

代码语言:javascript
复制
#include "FileMonitor.hpp"

int main(void)
{

    int m_EventID = FindFirstChangeNotification("/media/sf_P_DRIVE/FileMonitor/", 0, FILE_NOTIFY_CHANGE_FILE_NAME);

    int ret = WaitForSingleObject(m_EventID, 10000);
    printf("\nFinish %d", ret);
    fflush(stdout);

    FindNextChangeNotification(m_EventID);

    int ret2 = WaitForSingleObject(m_EventID, 10000);
    printf("\nFinish %d", ret2);

    FindCloseChangeNotification(1);
    printf("\nChangeNotification done");
    fflush(stdout);

    return 0;
}

如果你喜欢自己做这件事,试着使用轮询函数,你可以在线程中使用它。

代码语言:javascript
复制
        struct pollfd pfd = { th_params->fd, POLLIN, 0 };
        int ret = poll(&pfd, 1, 50);  // timeout of 50ms
        if (ret < 0) {
            printf("\failed poll");


        }
        else if (ret == 0) {
            // Timeout with no events, move on.
            printf("\nTimeout poll");

        }
        else {

            i = 0;
            int lenght = read(th_params->fd, buffer, 1024);
        }
票数 2
EN

Stack Overflow用户

发布于 2016-10-29 02:19:04

代码语言:javascript
复制
void FilesListener::refresh()
{
    char buffer[1024];

    int length = read( fd, buffer, EVENT_BUF_LEN ); 
    if ( length >=0 ) 
    {  
    ....
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40292684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档