xref: /original-bsd/usr.bin/tip/uucplock.c (revision 09da47ed)
1 /*
2  * Copyright (c) 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)uucplock.c	8.1 (Berkeley) 06/06/93";
10 #endif /* not lint */
11 
12 #include <sys/types.h>
13 #include <sys/file.h>
14 #include <sys/dir.h>
15 #include <errno.h>
16 #include "pathnames.h"
17 
18 /*
19  * uucp style locking routines
20  * return: 0 - success
21  * 	  -1 - failure
22  */
23 
24 uu_lock(ttyname)
25 	char *ttyname;
26 {
27 	extern int errno;
28 	int fd, pid;
29 	char tbuf[sizeof(_PATH_LOCKDIRNAME) + MAXNAMLEN];
30 	off_t lseek();
31 
32 	(void)sprintf(tbuf, _PATH_LOCKDIRNAME, ttyname);
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 		}
49 
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);
62 		}
63 		/* fall out and finish the locking process */
64 	}
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);
71 	}
72 	(void)close(fd);
73 	return(0);
74 }
75 
76 uu_unlock(ttyname)
77 	char *ttyname;
78 {
79 	char tbuf[sizeof(_PATH_LOCKDIRNAME) + MAXNAMLEN];
80 
81 	(void)sprintf(tbuf, _PATH_LOCKDIRNAME, ttyname);
82 	return(unlink(tbuf));
83 }
84