Commit | Line | Data |
---|---|---|
051b1e55 | 1 | /* |
abfba3de KB |
2 | * Copyright (c) 1988, 1993 |
3 | * The Regents of the University of California. All rights reserved. | |
0a6056a4 | 4 | * |
cb956e54 | 5 | * %sccs.include.redist.c% |
051b1e55 DF |
6 | */ |
7 | ||
05862919 | 8 | #ifndef lint |
abfba3de | 9 | static char sccsid[] = "@(#)uucplock.c 8.1 (Berkeley) %G%"; |
0a6056a4 | 10 | #endif /* not lint */ |
5b6474c5 | 11 | |
5b6474c5 | 12 | #include <sys/types.h> |
0a6056a4 KB |
13 | #include <sys/file.h> |
14 | #include <sys/dir.h> | |
15 | #include <errno.h> | |
435e8dff | 16 | #include "pathnames.h" |
5b6474c5 | 17 | |
0a6056a4 KB |
18 | /* |
19 | * uucp style locking routines | |
20 | * return: 0 - success | |
21 | * -1 - failure | |
5b6474c5 BJ |
22 | */ |
23 | ||
0a6056a4 KB |
24 | uu_lock(ttyname) |
25 | char *ttyname; | |
5b6474c5 | 26 | { |
0a6056a4 KB |
27 | extern int errno; |
28 | int fd, pid; | |
435e8dff | 29 | char tbuf[sizeof(_PATH_LOCKDIRNAME) + MAXNAMLEN]; |
0a6056a4 KB |
30 | off_t lseek(); |
31 | ||
435e8dff | 32 | (void)sprintf(tbuf, _PATH_LOCKDIRNAME, ttyname); |
0a6056a4 KB |
33 | fd = open(tbuf, O_RDWR|O_CREAT|O_EXCL, 0660); |
34 | if (fd < 0) { | |
35 | /* | |
36 | * file is already locked | |
37 | * check to see if the process holding the lock still exists | |
38 | */ | |
39 | fd = open(tbuf, O_RDWR, 0); | |
40 | if (fd < 0) { | |
41 | perror("lock open"); | |
42 | return(-1); | |
43 | } | |
44 | if (read(fd, &pid, sizeof(pid)) != sizeof(pid)) { | |
45 | (void)close(fd); | |
46 | perror("lock read"); | |
47 | return(-1); | |
48 | } | |
5b6474c5 | 49 | |
0a6056a4 KB |
50 | if (kill(pid, 0) == 0 || errno != ESRCH) { |
51 | (void)close(fd); /* process is still running */ | |
52 | return(-1); | |
53 | } | |
54 | /* | |
55 | * The process that locked the file isn't running, so | |
56 | * we'll lock it ourselves | |
57 | */ | |
58 | if (lseek(fd, 0L, L_SET) < 0) { | |
59 | (void)close(fd); | |
60 | perror("lock lseek"); | |
61 | return(-1); | |
5b6474c5 | 62 | } |
0a6056a4 | 63 | /* fall out and finish the locking process */ |
5b6474c5 | 64 | } |
0a6056a4 KB |
65 | pid = getpid(); |
66 | if (write(fd, (char *)&pid, sizeof(pid)) != sizeof(pid)) { | |
67 | (void)close(fd); | |
68 | (void)unlink(tbuf); | |
69 | perror("lock write"); | |
70 | return(-1); | |
5b6474c5 | 71 | } |
0a6056a4 KB |
72 | (void)close(fd); |
73 | return(0); | |
5b6474c5 BJ |
74 | } |
75 | ||
0a6056a4 KB |
76 | uu_unlock(ttyname) |
77 | char *ttyname; | |
5b6474c5 | 78 | { |
435e8dff | 79 | char tbuf[sizeof(_PATH_LOCKDIRNAME) + MAXNAMLEN]; |
5b6474c5 | 80 | |
435e8dff | 81 | (void)sprintf(tbuf, _PATH_LOCKDIRNAME, ttyname); |
0a6056a4 | 82 | return(unlink(tbuf)); |
5b6474c5 | 83 | } |