X-Git-Url: https://gapil.gnulinux.it/gitweb/?p=gapil.git;a=blobdiff_plain;f=sources%2FMutex.c;h=d0099982305d5d42c0b1c36ac3baead2afac66f1;hp=ddbb9b11354447b120502d9f6924db08a8c5e2fc;hb=bff17765a4aa5e979e0a72b70917c70254e97c98;hpb=17e39705eccbaa9111592907195befd05dbbed2d diff --git a/sources/Mutex.c b/sources/Mutex.c index ddbb9b1..d009998 100644 --- a/sources/Mutex.c +++ b/sources/Mutex.c @@ -22,7 +22,7 @@ * * Author: S. Piccardi Dec. 2002 * - * $Id: Mutex.c,v 1.2 2002/12/03 22:30:11 piccardi Exp $ + * $Id: Mutex.c,v 1.3 2002/12/05 23:38:22 piccardi Exp $ * *****************************************************************************/ #include /* IPC semaphore declarations */ @@ -109,3 +109,63 @@ int MutexUnlock(int sem_id) { return semop(sem_id, &sem_ulock, 1); } +/***************************************************************************** + * + * File locking mutex + * + * Create a mutex usinf file locking. Use file locking to lock a file + * as a mutex request, and unlock it as a mutex release. + * + * Author: S. Piccardi Dec. 2002 + * + *****************************************************************************/ +/* + * Function LockMutex: lock a file (creating it if not existent). + * + * Input: a filename + * Output: a return code (0 OK, -1 KO) + */ +int LockMutex(const char *path_name) +{ + int fd, res; + struct flock lock; /* file lock structure */ + /* first open the file (creating it if not existent) */ + if ( (fd = open(path_name, O_EXCL|O_CREAT)) < 0) { /* first open file */ + return fd; + } + /* set flock structure */ + lock.l_type = F_WRLCK; /* set type: read or write */ + lock.l_whence = SEEK_SET; /* start from the beginning of the file */ + lock.l_start = 0; /* set the start of the locked region */ + lock.l_len = 0; /* set the length of the locked region */ + /* do locking */ + if ( (res = fcntl(fd, F_SETLKW, &lock)) < 0 ) { + return res; + } + return 0; +} +/* + * Function UnlockMutex: unlock a file. + * + * Input: a filename + * Output: a return code (0 OK, -1 KO) + */ +int UnlockMutex(const char *path_name) +{ + int fd, res; + struct flock lock; /* file lock structure */ + /* first open the file */ + if ( (fd = open(path_name, O_RDWR)) < 0) { /* first open file */ + return fd; + } + /* set flock structure */ + lock.l_type = F_UNLCK; /* set type: unlock */ + lock.l_whence = SEEK_SET; /* start from the beginning of the file */ + lock.l_start = 0; /* set the start of the locked region */ + lock.l_len = 0; /* set the length of the locked region */ + /* do locking */ + if ( (res = fcntl(fd, F_SETLK, &lock)) < 0 ) { + return res; + } + return 0; +}