问题
How can I lock a file for a specified period of time (10 seconds) using the C language in Ubuntu Linux ?
回答1:
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();
...
回答2:
Use fcntl(2)
to lock the file, then use alarm(2)
to call your SIGALRM
handler which will then unlock it.
来源:https://stackoverflow.com/questions/2058891/locking-and-unlocking-files-using-c-api-in-ubuntu-linux