From 6f15b324fbf17cd7d387654a479bf37226558137 Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Sat, 4 May 2019 14:03:37 +0200 Subject: [PATCH] serial: delete stale lock files If microcom crashes, e.g. due to the buffer underflow described in #10, it may leave a stale lock file behind. Teach microcom detection of these stale lock files. Signed-off-by: Ahmad Fatoum --- serial.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/serial.c b/serial.c index 97b5448..3fb9a9b 100644 --- a/serial.c +++ b/serial.c @@ -182,12 +182,34 @@ struct ios_ops * serial_init(char *device) fd = open(lockfile, O_RDWR | O_CREAT | O_EXCL, 0444); if (fd < 0) { if (errno == EEXIST) { + char pidbuf[12]; + ssize_t nbytes = 0; if (opt_force) { printf("lockfile for port exists, ignoring\n"); serial_unlock(); goto relock; } + fd = open(lockfile, O_RDONLY); + if (fd < 0) + main_usage(3, "lockfile for port can't be opened", device); + + do { + ret = read(fd, &pidbuf[nbytes], sizeof(pidbuf) - nbytes - 1); + nbytes += ret; + } while (ret > 0 && nbytes < sizeof (pidbuf) - 1); + + if (ret >= 0) { + pidbuf[nbytes] = '\0'; + ret = sscanf(pidbuf, "%10ld\n", &pid); + + if (ret == 1 && kill(pid, 0) < 0 && errno == ESRCH) { + printf("lockfile contains stale pid, ignoring\n"); + serial_unlock(); + goto relock; + } + } + main_usage(3, "lockfile for port exists", device); }