Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux stat call with a timeout

Tags:

linux

Is there a way to make the Linux stat system call with a timeout?

I'm using a distributed file system, and in theory all of my file system calls should be answered promptly, in practice they are not. After a fixed amount of time I'd rather have a timeout and an error code than continue to hang.

I've tried spawning off the request in another thread, but that has some undesirable interactions with gdb and is a pretty roundabout way of expressing what I really want: a timeout.

like image 676
razeh Avatar asked Feb 16 '18 16:02

razeh


1 Answers

Assuming you're using C, and you can set safely the SIGALARM handler, you can use code similar to this, just with a different library call: Can statvfs block on certain network devices? How to handle that case?

Pretty much cut-and-paste the code and change statvfs to 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 );
}
like image 94
Andrew Henle Avatar answered Nov 17 '22 12:11

Andrew Henle