Rev | Line | |
---|
[9] | 1 | #include <lib.h>
|
---|
| 2 | #include <errno.h>
|
---|
| 3 | #include <sys/types.h>
|
---|
| 4 | #include <unistd.h>
|
---|
| 5 | #include <string.h>
|
---|
| 6 | #include <fcntl.h>
|
---|
| 7 | #include <stdio.h>
|
---|
| 8 | #if _ANSI
|
---|
| 9 | #include <stdlib.h>
|
---|
| 10 | #endif
|
---|
| 11 |
|
---|
| 12 | typedef enum {
|
---|
| 13 | False, True
|
---|
| 14 | } BOOLEAN;
|
---|
| 15 |
|
---|
| 16 | #define LOCKDIR "/tmp/" /* or /usr/tmp/ as the case may be */
|
---|
| 17 | #define MAXTRIES 3
|
---|
| 18 | #define NAPTIME (unsigned int)5
|
---|
| 19 |
|
---|
| 20 | PRIVATE _PROTOTYPE( char *lockpath, (char *name));
|
---|
| 21 | _PROTOTYPE( void syserr, (char *errstring));
|
---|
| 22 | _PROTOTYPE( BOOLEAN lock, (char *name));
|
---|
| 23 | _PROTOTYPE( void unlock, (char *name));
|
---|
| 24 |
|
---|
| 25 | void
|
---|
| 26 | syserr(errstring)
|
---|
| 27 | char *errstring;
|
---|
| 28 | {
|
---|
| 29 | fprintf(stderr,"couldn't %s\n", errstring);
|
---|
| 30 | exit(1);
|
---|
| 31 | }
|
---|
| 32 |
|
---|
| 33 | BOOLEAN lock(name) /* acquire lock */
|
---|
| 34 | char *name;
|
---|
| 35 | {
|
---|
| 36 | char *path;
|
---|
| 37 | int fd, tries;
|
---|
| 38 |
|
---|
| 39 | path = lockpath(name);
|
---|
| 40 | tries = 0;
|
---|
| 41 | while ((fd = creat(path, 0)) == -1 && errno == EACCES) {
|
---|
| 42 | if (++tries >= MAXTRIES) return(False);
|
---|
| 43 | sleep(NAPTIME);
|
---|
| 44 | }
|
---|
| 45 | if (fd == -1 || close(fd) == -1) syserr("lock");
|
---|
| 46 | return(True);
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | void unlock(name) /* free lock */
|
---|
| 50 | char *name;
|
---|
| 51 | {
|
---|
| 52 | if (unlink(lockpath(name)) == -1) syserr("unlock");
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | PRIVATE char *lockpath(name) /* generate lock file path */
|
---|
| 56 | char *name;
|
---|
| 57 | {
|
---|
| 58 | PRIVATE char path[20];
|
---|
| 59 |
|
---|
| 60 | strcpy(path, LOCKDIR);
|
---|
| 61 | return(strcat(path, name));
|
---|
| 62 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.