Versione finale del client ECHO su TCP, con esempio di uso della funzione
[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     /* set flock structure */
16     lock.l_type = F_WRLCK;    /* set type: read or write */
17     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
18     lock.l_start = 0;         /* set the start of the locked region */
19     lock.l_len = 0;           /* set the length of the locked region */
20     /* do locking */
21     return fcntl(fd, F_SETLKW, &lock);
22 }
23 /* Function UnlockMutex: unlock a file. */
24 int UnlockMutex(int fd)
25 {
26     struct flock lock;        /* file lock structure */
27     /* set flock structure */
28     lock.l_type = F_UNLCK;    /* set type: unlock */
29     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
30     lock.l_start = 0;         /* set the start of the locked region */
31     lock.l_len = 0;           /* set the length of the locked region */
32     /* do locking */
33     return fcntl(fd, F_SETLK, &lock);
34 }
35 /* Function RemoveMutex: remove a mutex (unlinking the lock file). */
36 int RemoveMutex(const char *path_name)
37 {
38     return unlink(path_name);
39 }
40 /* Function ReadMutex: read a mutex status. */
41 int ReadMutex(int fd)
42 {
43     int res;
44     struct flock lock;        /* file lock structure */
45     /* set flock structure */
46     lock.l_type = F_WRLCK;    /* set type: unlock */
47     lock.l_whence = SEEK_SET; /* start from the beginning of the file */
48     lock.l_start = 0;         /* set the start of the locked region */
49     lock.l_len = 0;           /* set the length of the locked region */
50     /* do locking */
51     if ( (res = fcntl(fd, F_GETLK, &lock)) ) {
52         return res;
53     }
54     return lock.l_type;
55 }