xref: /original-bsd/usr.bin/tip/uucplock.c (revision 5cf7f382)
1 /*
2  * Copyright (c) 1988 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 static char sccsid[] = "@(#)uucplock.c	5.3 (Berkeley) 09/02/88";
20 #endif /* not lint */
21 
22 #include <sys/types.h>
23 #include <sys/file.h>
24 #include <sys/dir.h>
25 #include <errno.h>
26 
27 /* pick the directory naming scheme you are using */
28 
29 #define LOCKDIRNAME	"/usr/spool/uucp/LCK..%s"	/**/
30 /* #define LOCKDIRNAME	"/usr/spool/uucp/LCK/LCK..%s"	/**/
31 
32 /*
33  * uucp style locking routines
34  * return: 0 - success
35  * 	  -1 - failure
36  */
37 
38 uu_lock(ttyname)
39 	char *ttyname;
40 {
41 	extern int errno;
42 	int fd, pid;
43 	char tbuf[sizeof(LOCKDIRNAME) + MAXNAMLEN];
44 	off_t lseek();
45 
46 	(void)sprintf(tbuf, LOCKDIRNAME, ttyname);
47 	fd = open(tbuf, O_RDWR|O_CREAT|O_EXCL, 0660);
48 	if (fd < 0) {
49 		/*
50 		 * file is already locked
51 		 * check to see if the process holding the lock still exists
52 		 */
53 		fd = open(tbuf, O_RDWR, 0);
54 		if (fd < 0) {
55 			perror("lock open");
56 			return(-1);
57 		}
58 		if (read(fd, &pid, sizeof(pid)) != sizeof(pid)) {
59 			(void)close(fd);
60 			perror("lock read");
61 			return(-1);
62 		}
63 
64 		if (kill(pid, 0) == 0 || errno != ESRCH) {
65 			(void)close(fd);	/* process is still running */
66 			return(-1);
67 		}
68 		/*
69 		 * The process that locked the file isn't running, so
70 		 * we'll lock it ourselves
71 		 */
72 		if (lseek(fd, 0L, L_SET) < 0) {
73 			(void)close(fd);
74 			perror("lock lseek");
75 			return(-1);
76 		}
77 		/* fall out and finish the locking process */
78 	}
79 	pid = getpid();
80 	if (write(fd, (char *)&pid, sizeof(pid)) != sizeof(pid)) {
81 		(void)close(fd);
82 		(void)unlink(tbuf);
83 		perror("lock write");
84 		return(-1);
85 	}
86 	(void)close(fd);
87 	return(0);
88 }
89 
90 uu_unlock(ttyname)
91 	char *ttyname;
92 {
93 	char tbuf[sizeof(LOCKDIRNAME) + MAXNAMLEN];
94 
95 	(void)sprintf(tbuf, LOCKDIRNAME, ttyname);
96 	return(unlink(tbuf));
97 }
98