Fopen / fdopen hangs on broken network shares or remote USB devices
I am creating a background service for an embedded Linux device in C. Every hour a file is read from either a network share or a USB device, but if a network or USB device was connected, fopen never returns and the service freezes. I am not allowed to use async methods like pthread or fork to read this file, so I am looking for a timed out solution or something non-blocking to check if the file (or device) is available.
Below are code examples that depend 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: fopen's answers don't return , doesn't solve my problem. I know why this is happening, but the service shouldn't wait for an unresponsive device. as described above, I need a non-blocking solution or timeout.
source to share
No one has answered this question yet
See similar questions:
or similar: