Skip to content

Commit 91a6aec

Browse files
committed
serial: delete stale lock files
If microcom crashes, e.g. due to the buffer underflow described in pengutronix#10, it may leave a stale lock file behind. Teach microcom detection of these stale lock files. Note that this is racy, two processes may detect a stale lock file and one might unlink the other's lock. Signed-off-by: Ahmad Fatoum <[email protected]>
1 parent 05c9da8 commit 91a6aec

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

serial.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,12 +182,34 @@ struct ios_ops * serial_init(char *device)
182182
fd = open(lockfile, O_RDWR | O_CREAT | O_EXCL, 0444);
183183
if (fd < 0) {
184184
if (errno == EEXIST) {
185+
char pidbuf[12];
186+
ssize_t nbytes = 0;
185187
if (opt_force) {
186188
printf("lockfile for port exists, ignoring\n");
187189
serial_unlock();
188190
goto relock;
189191
}
190192

193+
fd = open(lockfile, O_RDONLY);
194+
if (fd < 0)
195+
main_usage(3, "lockfile for port can't be opened", device);
196+
197+
do {
198+
ret = read(fd, &pidbuf[nbytes], sizeof(pidbuf) - nbytes - 1);
199+
nbytes += ret;
200+
} while (ret > 0 && nbytes < sizeof (pidbuf) - 1);
201+
202+
if (ret >= 0) {
203+
pidbuf[nbytes] = '\0';
204+
ret = sscanf(pidbuf, "%10ld\n", &pid);
205+
206+
if (ret == 1 && kill(pid, 0) < 0 && errno == ESRCH) {
207+
printf("lockfile contains stale pid, ignoring\n");
208+
serial_unlock();
209+
goto relock;
210+
}
211+
}
212+
191213
main_usage(3, "lockfile for port exists", device);
192214
}
193215

0 commit comments

Comments
 (0)