dev/c/fcntl_ex/fcntl_lockfile.c

103 lines
1.9 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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>
#include <string.h>
/* не работает с nfs */
void ex1()
{
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();
}
/* только для 1-го процесса */
void ex2()
{
FILE *f = fopen("fcntl_lockfile.c", "wb");
if(f != NULL && !ftrylockfile(f)) {
flockfile(f);
puts("Success!");
} else
puts("Failed!");
getchar();
}
/* с cifs не работает */
void sighandler(int signum)
{
printf("signal %d received\n", signum);
}
void ex3()
{
signal(SIGPOLL, sighandler);
int fd = open("fcntl_lockfile.c", O_RDWR | O_NONBLOCK);
//~ int fd = open("/mnt/smb/fs04/Users/ПРОЕКТЫ/Отчетник Климов/lock_ex", O_RDWR | O_NONBLOCK);
//~ int fd = open("/mnt/smb/kolan/shared/lock_ex", O_RDWR | O_NONBLOCK);
if (fd == -1)
err(errno, "open()");
if (fcntl(fd, F_SETLEASE, F_WRLCK) == -1)
err(errno, "fcntl()");
puts("Success!");
getchar();
}
/* зашибись - метод :)
* Консультативная (advisory) блокировка... */
void ex4()
{
signal(SIGPOLL, sighandler);
//~ int fd = open("fcntl_lockfile.c", O_RDWR | O_NONBLOCK);
//~ int fd = open("/mnt/smb/fs04/Users/ПРОЕКТЫ/Отчетник Климов/lock_ex", O_RDWR | O_NONBLOCK);
int fd = open("/mnt/smb/kolan/shared/lock_ex", O_RDWR | O_NONBLOCK);
if (fd == -1)
err(errno, "open()");
struct flock flck;
memset(&flck, 0, sizeof(flck));
flck.l_type = F_WRLCK;
if (fcntl(fd, F_SETLK, &flck) == -1)
err(errno, "fcntl()");
puts("Success!");
getchar();
}
int main()
{
//~ ex1();
//~ ex2();
//~ ex3();
ex4();
return 0;
}