fcntl lockfile example

This commit is contained in:
Kolan Sh 2011-06-30 18:43:16 +04:00
parent 5934035bf6
commit 4ca18afee7
1 changed files with 62 additions and 0 deletions

View File

@ -0,0 +1,62 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/fcntl.h>
#include <stdio.h>
#include <sys/file.h>
#include <unistd.h>
#include <signal.h>
#include <err.h>
#include <errno.h>
void sighandler(int signum)
{
printf("signal %d received\n", signum);
}
int main()
{
/* не работает с nfs
FILE *f = fopen("fcntl_lockfile.c", "wb");
if(f != NULL && !flock(fileno(f), LOCK_EX | LOCK_NB))// !ftrylockfile(f))
puts("Success!");
else
puts("Failed!");
getchar();
return 0;
*/
/* 1 процесс
FILE *f = fopen("fcntl_lockfile.c", "wb");
if(f != NULL && !ftrylockfile(f)) {
flockfile(f);
puts("Success!");
} else
puts("Failed!");
getchar();
return 0;
*/
signal(SIGPOLL, sighandler);
int fd = open("fcntl_lockfile.c", O_RDWR | O_NONBLOCK);
if (fd == -1)
err(errno, "open()");
if (fcntl(fd, F_SETLEASE, F_WRLCK) == -1)
err(errno, "fcntl()");
puts("Success!");
getchar();
return 0;
}