-/********************************************************************
- * Code for locking/unlocking the serial device.
- * This code is derived from chat.c.
- */
-
-/*
- * lock - create a lock file for the named device
- */
-
-int lock (char *dev)
-{
-#ifdef LOCKLIB
- int result;
- lock_file = strdup(dev);
- if (lock_file == NULL)
- novm("lock file name");
- result = mklock (dev, (void *) 0);
-
- if (result > 0) {
- notice("Device %s is locked by pid %d", dev, result);
- free (lock_file);
- lock_file = NULL;
- result = -1;
- }
- else {
- if (result < 0) {
- error("Can't create lock file %s", lock_file);
- free (lock_file);
- lock_file = NULL;
- result = -1;
- }
- }
- return (result);
-#else
- char hdb_lock_buffer[12];
- int fd, n;
- int pid = getpid();
- char *p;
- size_t l;
-
- p = strrchr(dev, '/');
- if (p != NULL)
- dev = ++p;
-
- l = strlen(LOCK_PREFIX) + strlen(dev) + 1;
- lock_file = malloc(l);
- if (lock_file == NULL)
- novm("lock file name");
-
- slprintf(lock_file, l, "%s%s", LOCK_PREFIX, dev);
-/*
- * Attempt to create the lock file at this point.
- */
- while (1) {
- fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644);
- if (fd >= 0) {
- pid = getpid();
-#ifndef PID_BINARY
- slprintf(hdb_lock_buffer, sizeof(hdb_lock_buffer), "%010d\n", pid);
- write (fd, hdb_lock_buffer, 11);
-#else
- write(fd, &pid, sizeof (pid));
-#endif
- close(fd);
- return 0;
- }
-/*
- * If the file exists then check to see if the pid is stale
- */
- if (errno == EEXIST) {
- fd = open(lock_file, O_RDONLY, 0);
- if (fd < 0) {
- if (errno == ENOENT) /* This is just a timing problem. */
- continue;
- break;
- }
-
- /* Read the lock file to find out who has the device locked */
- n = read (fd, hdb_lock_buffer, 11);
- close (fd);
- if (n < 0) {
- error("Can't read pid from lock file %s", lock_file);
- break;
- }
-
- /* See the process still exists. */
- if (n > 0) {
-#ifndef PID_BINARY
- hdb_lock_buffer[n] = '\0';
- sscanf (hdb_lock_buffer, " %d", &pid);
-#else
- pid = ((int *) hdb_lock_buffer)[0];
-#endif
- if (pid == 0 || pid == getpid()
- || (kill(pid, 0) == -1 && errno == ESRCH))
- n = 0;
- }
-
- /* If the process does not exist then try to remove the lock */
- if (n == 0 && unlink (lock_file) == 0) {
- notice("Removed stale lock on %s (pid %d)",
- dev, pid);
- continue;
- }
-
- notice("Device %s is locked by pid %d", dev, pid);
- break;
- }
-
- error("Can't create lock file %s: %m(%d)", lock_file, errno);
- break;