Search code examples
cflock

C: How to add timeout on flock?


In C programming, is there a way to achieve timeout on flock()?

Thanks.

#include <sys/file.h>

int flock(int fd, int operation);

Solution

  • You can use SIG_ALARM to do it. http://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html It is kind of tricky though, especially if you are dealing with multiple threads. You would have to make sure that your system delivers the sig alarm to the thread that set it always, and it might not be the case... in which case you would need to play with pthread_sigmask http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_sigmask.html to make sure that only your thread has the signal enabled... but what if 2 threads are blocking on flock at the same time? You will need to add some kind of mutex wrapper for that.