1 # include "../hdr/macros.h" 2 # include "errno.h" 3 SCCSID(@(#)lockit 2.1); 4 /* 5 Process semaphore. 6 Try repeatedly (`count' times) to create `lockfile' mode 444. 7 Sleep 10 seconds between tries. 8 If `lockfile' is successfully created, write the process ID 9 `pid' in `lockfile' (in binary), and return 0. 10 If `lockfile' exists and it hasn't been modified within the last 11 minute, and either the file is empty or the process ID contained 12 in the file is not the process ID of any existing process, 13 `lockfile' is removed and it tries again to make `lockfile'. 14 After `count' tries, or if the reason for the create failing 15 is something other than EACCES, return xmsg(). 16 17 Unlockit will return 0 if the named lock exists, contains 18 the given pid, and is successfully removed; -1 otherwise. 19 */ 20 21 22 lockit(lockfile,count,pid) 23 register char *lockfile; 24 register unsigned count; 25 unsigned pid; 26 { 27 register int fd; 28 unsigned opid; 29 long ltime; 30 extern int errno; 31 32 for (++count; --count; sleep(10)) { 33 if ((fd=creat(lockfile,0444)) >= 0) { 34 write(fd,&pid,sizeof(pid)); 35 close(fd); 36 return(0); 37 } 38 if (errno == ENFILE) { 39 unlink(lockfile); 40 ++count; 41 continue; 42 } 43 if (errno != EACCES) 44 return(xmsg(lockfile,"lockit")); 45 if (exists(lockfile)) { 46 time(<ime); 47 ltime -= Statbuf.st_mtime; 48 if ((fd = open(lockfile,0)) < 0) 49 continue; 50 if (ltime < 60L) 51 sleep(60); 52 if (read(fd,&opid,sizeof(opid)) != sizeof(opid)) { 53 close(fd); 54 unlink(lockfile); 55 continue; 56 } 57 close(fd); 58 if (kill(opid,0) == -1 && errno == ESRCH) { 59 unlink(lockfile); 60 continue; 61 } 62 } 63 } 64 return(-1); 65 } 66 67 68 unlockit(lockfile,pid) 69 register char *lockfile; 70 unsigned pid; 71 { 72 register int fd, n; 73 unsigned opid; 74 75 if ((fd = open(lockfile,0)) < 0) 76 return(-1); 77 n = read(fd,&opid,sizeof(opid)); 78 close(fd); 79 if (n == sizeof(opid) && opid == pid) 80 return(unlink(lockfile)); 81 else 82 return(-1); 83 } 84