Altre ripuliture
[gapil.git] / listati / MutexLocking.c
1 /* Function CreateMutex: Create a mutex using file locking. */
2 int CreateMutex(const char *path_name)
3 {
4     return open(path_name, O_EXCL|O_CREAT);
5 }
6 /* Function UnlockMutex: unlock a file. */
7 int FindMutex(const char *path_name)
8 {
9     return open(path_name, O_RDWR);
10 }
11 /* Function LockMutex: lock mutex using file locking. */
12 int LockMutex(int fd)
13 {
14     struct flock lock;        /* file lock structure */
15     lock.l_type = F_WRLCK;    /* set type: read or write */
16     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
17     lock.l_start = 0;         /* set the start of the locked region */
18     lock.l_len = 0;           /* set the length of the locked region */
19     /* do locking */
20     return fcntl(fd, F_SETLKW, &lock);
21 }
22 /* Function UnlockMutex: unlock a file. */
23 int UnlockMutex(int fd)
24 {
25     struct flock lock;        /* file lock structure */
26     lock.l_type = F_UNLCK;    /* set type: unlock */
27     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
28     lock.l_start = 0;         /* set the start of the locked region */
29     lock.l_len = 0;           /* set the length of the locked region */
30     /* do locking */
31     return fcntl(fd, F_SETLK, &lock);
32 }
33 /* Function RemoveMutex: remove a mutex (unlinking the lock file). */
34 int RemoveMutex(const char *path_name)
35 {
36     return unlink(path_name);
37 }
38 /* Function ReadMutex: read a mutex status. */
39 int ReadMutex(int fd)
40 {
41     int res;
42     struct flock lock;        /* file lock structure */
43     lock.l_type = F_WRLCK;    /* set type: unlock */
44     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
45     lock.l_start = 0;         /* set the start of the locked region */
46     lock.l_len = 0;           /* set the length of the locked region */
47     /* do locking */
48     if ( (res = fcntl(fd, F_GETLK, &lock)) ) {
49         return res;
50     }
51     return lock.l_type;
52 }