-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialize_lock.c
53 lines (42 loc) · 1.16 KB
/
serialize_lock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "serialize_lock.h"
const char *serialize_lock_fname = "/run/lock/serialize_lock";
int serialize_lock_fd = -1;
int serialize_lock(int no_wait)
{
int fd;
fd = open(serialize_lock_fname,
O_RDWR | /* open the file for both read and write access */
O_CREAT | /* create file if it does not already exist */
O_CLOEXEC , /* close on execute */
S_IRUSR | /* user permission: read */
S_IWUSR ); /* user permission: write */
if (fd == -1)
return -1;
if (no_wait) {
/* try to lock the "semaphore", if busy report that */
if (lockf( fd, F_TLOCK, 0 ) == -1) {
close(fd);
return errno == EAGAIN? 0: -1;
}
} else {
/* lock the "semaphore", wait until available */
if (lockf( fd, F_LOCK, 0 ) == -1)
return -1;
}
serialize_lock_fd = fd;
return 1;
}
void serialize_unlock(void)
{
int fd = serialize_lock_fd;
if (fd == -1)
return;
/* close() automatically releases the file lock */
/* so technically the call with F_ULOCK is not necessary */
lockf( fd, F_ULOCK, 0 );
close( fd );
serialize_lock_fd = -1;
}