-
-/* Lock the lock file named LFNAME.
- If MODE is O_WRONLY, we do so even if it is already locked.
- If MODE is O_WRONLY | O_EXCL | O_CREAT, we do so only if it is free.
- Return 1 if successful, 0 if not. */
-
-static int
-lock_file_1 (CONST char *lfname, int mode)
-{
- REGISTER int fd;
- char buf[20];
-
- if ((fd = open (lfname, mode, 0666)) >= 0)
- {
-#if defined(WINDOWSNT)
- chmod(lfname, _S_IREAD|_S_IWRITE);
-#elif defined(USG)
- chmod (lfname, 0666);
-#else
- fchmod (fd, 0666);
-#endif
- sprintf (buf, "%ld ", (long) getpid ());
- write (fd, buf, strlen (buf));
- close (fd);
- return 1;
- }
- else
- return 0;
-}
-
-/* Lock the lock named LFNAME if possible.
- Return 0 in that case.
- Return positive if lock is really locked by someone else.
- Return -1 if cannot lock for any other reason. */
-
-static int
-lock_if_free (CONST char *lfname)
-{
- REGISTER int clasher;
-
- while (lock_file_1 (lfname, O_WRONLY | O_EXCL | O_CREAT) == 0)
- {
- if (errno != EEXIST)
- return -1;
- clasher = current_lock_owner (lfname);
- if (clasher != 0)
- if (clasher != getpid ())
- return (clasher);
- else return (0);
- /* Try again to lock it */
- }
- return 0;
-}
-
-/* Return the pid of the process that claims to own the lock file LFNAME,
- or 0 if nobody does or the lock is obsolete,
- or -1 if something is wrong with the locking mechanism. */
-
-static int
-current_lock_owner (CONST char *lfname)
-{
- int owner = current_lock_owner_1 (lfname);
- if (owner == 0 && errno == ENOENT)
- return (0);
- /* Is it locked by a process that exists? */
- if (owner != 0 && (kill (owner, 0) >= 0 || errno == EPERM))
- return (owner);
- if (unlink (lfname) < 0)
- return (-1);
- return (0);
-}
-
-static int
-current_lock_owner_1 (CONST char *lfname)
-{
- REGISTER int fd;
- char buf[20];
- int tem;
-
- fd = open (lfname, O_RDONLY, 0666);
- if (fd < 0)
- return 0;
- tem = read (fd, buf, sizeof buf);
- close (fd);
- return (tem <= 0 ? 0 : atoi (buf));
-}
-
-\f