2 * lock.c - lock/unlock the serial device.
4 * This code is derived from chat.c.
10 # if defined(SUNOS) && SUNOS >= 41
20 # define LOCK_PREFIX "/var/spool/lock/LCK.."
24 # define LOCK_PREFIX "/usr/spool/locks/LCK.."
26 # define LOCK_PREFIX "/usr/spool/uucp/LCK.."
29 #endif /* LOCK_PREFIX */
31 static char *lock_file;
34 * Create a lock file for the named lock device
39 char hdb_lock_buffer[12];
44 if ((p = strrchr(dev, '/')) != NULL)
46 lock_file = malloc(strlen(LOCK_PREFIX) + strlen(dev) + 1);
47 if (lock_file == NULL)
49 strcat(strcpy(lock_file, LOCK_PREFIX), dev);
51 while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
53 && (fd = open(lock_file, O_RDONLY, 0)) >= 0) {
54 /* Read the lock file to find out who has the device locked */
56 n = read(fd, hdb_lock_buffer, 11);
58 hdb_lock_buffer[n] = 0;
59 pid = atoi(hdb_lock_buffer);
62 n = read(fd, &pid, sizeof(pid));
65 syslog(LOG_ERR, "Can't read pid from lock file %s", lock_file);
68 if (kill(pid, 0) == -1 && errno == ESRCH) {
69 /* pid no longer exists - remove the lock file */
70 if (unlink(lock_file) == 0) {
72 syslog(LOG_NOTICE, "Removed stale lock on %s (pid %d)",
76 syslog(LOG_WARNING, "Couldn't remove stale lock on %s",
79 syslog(LOG_NOTICE, "Device %s is locked by pid %d",
84 syslog(LOG_ERR, "Can't create lock file %s: %m", lock_file);
91 sprintf(hdb_lock_buffer, "%10d\n", getpid());
92 write(fd, hdb_lock_buffer, 11);
95 write(fd, &pid, sizeof pid);
103 * Remove our lockfile