fcntl lockfile example
This commit is contained in:
parent
5934035bf6
commit
4ca18afee7
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue