views:

212

answers:

2

Hello,

How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?

+3  A: 

It works like this:

#include <io.h>
#include <sys/file.h>
...
int f = open ("filename", O_RDONLY);
if (f < 0)
       error();
if (flock (f, LOCK_EX))
       error();
sleep (10);

if (flock (f, LOCK_UN))
       error();
...
wallyk
Keep in mind that these are not mandatory locks they're advisory locks - meaning everyone that uses the file need to flock it too. If they don't they're free to manipulate the file.
nos
+1  A: 

Use fcntl(2) to lock the file, then use alarm(2) to call your SIGALRM handler which will then unlock it.

Ignacio Vazquez-Abrams
Is it safe to call `flock` in a signal handler?
John Ledbetter
Hrm. `signal(7)` says no. `fcntl(2)` should be fine though.
Ignacio Vazquez-Abrams