Linux stat call with timeout

Is there a way to make a Linux system call time out?

I use a distributed file system, and theoretically all my calls to the file system should be answered quickly, in practice this is not so. After a certain amount of time, I prefer to have a timeout and an error code than keep hanging.

I tried canceling the request in another thread, but it has some unwanted interactions with gdb and a pretty cool way to express what I really want: timeout.

+6
source share
1 answer

, C, SIGALARM, , , : statvfs ? ?

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 );
}
+2

All Articles