Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout fwrite call to keep it from blocking

Is there a method to keep fwrite from blocking, like say using timeouts?

The scenario is this: I need to make a fwrite call (since I am largely reusing a code , I need to stick to it) on a network. However if I pull off the network cable, the fwrite blocks. Is there a workaround? Any help/suggestions will be greatly appreciated.

like image 489
neorg Avatar asked Dec 20 '22 21:12

neorg


1 Answers

Switch an underlying file descriptor to non-blocking mode:

int fd = fdnum(stream);
int f = fcntl(fd, F_GETFL, 0);
f |= O_NONBLOCK;
fcntl(fd, F_SETFL, f);

After this a call to fwrite() will immediately return and set errno to EAGAIN if the file descriptor is not ready for being written to. Calling it in a loop and using sleeps you can easily implement whatever timeout behavior you need.

like image 159
Alex Bakulin Avatar answered Dec 24 '22 02:12

Alex Bakulin