代码之家  ›  专栏  ›  技术社区  ›  razeh

Linux stat调用超时

  •  8
  • razeh  · 技术社区  · 8 年前

    有没有办法让Linux stat系统调用超时?

    我使用的是分布式文件系统,从理论上讲,我所有的文件系统调用都应该得到及时响应,但实际上并不是这样。在一段固定的时间之后,我宁愿有一个超时和一个错误代码,也不愿继续挂起。

    我尝试在另一个线程中派生请求,但这与gdb有一些不需要的交互,并且是表达我真正想要的东西的一种非常迂回的方式:超时。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Andrew Henle    8 年前

    假设您使用的是C,并且可以安全地设置 SIGALARM 处理程序,您可以使用类似的代码,只需使用不同的库调用即可: Can statvfs block on certain network devices? How to handle that case?

    基本上是剪切粘贴代码并进行更改 statvfs stat :

    #include <sigaction.h>
    #include <sys/stat.h>
    #include <unistd.h>
    #include <string.h>
    
    // alarm handler doesn't need to do anything
    // other than simply exist
    static void alarm_handler( int sig )
    {
        return;
    }
    
     .
     .
     .
    
    // stat() with a timeout measured in seconds
    // will return -1 with errno set to EINTR should
    // it time out
    int statvfs_try( const char *path, struct stat *s, unsigned int seconds )
    {
        struct sigaction newact;
        struct sigaction oldact;
    
        // make sure they're entirely clear (yes I'm paranoid...)
        memset( &newact, 0, sizeof( newact ) );
        memset( &oldact, 0, sizeof( oldact) );
    
        sigemptyset( &newact.sa_mask );
    
        // note that does not have SA_RESTART set, so
        // stat() should be interrupted on a signal
        // (hopefully your libc doesn't restart it...)
        newact.sa_flags = 0;
        newact.sa_handler = alarm_handler;
        sigaction( SIGALRM, &newact, &oldact );
    
        alarm( seconds );
    
        // clear errno
        errno = 0;
        int rc = stat( path, s );
    
        // save the errno value as alarm() and sigaction() might change it
        int save_errno = errno;
    
        // clear any alarm and reset the signal handler
        alarm( 0 );
        sigaction( SIGALRM, &oldact, NULL );
    
        errno = saved_errno;
        return( rc );
    }