fopen/fdopen freezes on broken network shares or removed usb devices

Viewed 305

I am building a background service for a embedded linux device in C. Every hour a file is read either from a network share or a usb device, but if the network or usb device was plugged out, fopen never returns and the service freezes. I am not allowed to use async methods like pthread or fork to read that file, so i am looking for a solution with a timeout or something non-blocking to test if the file (or device) is available.

The code examples below are freezing on fopen/fdopen.

FILE* f = fopen("/path/to/file", "r"); //freezes if device not available;
if(f)
{
    < .. read file .. >
    fclose(f);
}

////////////////////////////////////////////

FILE* f = NULL;
int fd  = open("/path/to/file", O_RDONLY|O_NONBLOCK);
if(fd>=0)
{
    f= fdopen(fd, "r");//freezes if device not available
}

if(f)
{
    < .. read file .. >
    fclose(f);
}
else
{
    if(fd>=0){close(fd);}
}

edit: the answers for fopen does not return do not solve my issue. i do know why this is happening, but the service must not wait for a unresponsive device. as described above, i need a non blocking solution or a timeout.

0 Answers
Related