Run one game per profile at a time.

Nothing kept a second copy of the game off the same profile (a double start, or the restart going ahead after 30 s
while the old process still ran). Its start took the first copy's commit in progress for an interrupted one and
deleted it, removed the first copy's working copy under its open files, and then both wrote into one save-tx/work,
so saves were lost or mixed. The save storage now takes <profile>/instance.lock (plat_lock_file: a file no other
process can open on Windows, flock on Linux) and a second copy stops with "another copy of the game is running".
--probe-fs gives the lock back before deleting its temporary profile and passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
chrg6
2026-11-08 09:33:14 -05:00
parent dc1afcb54f
commit 8bd2d6aa31
4 changed files with 100 additions and 0 deletions

View File

@@ -17,6 +17,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
@@ -731,6 +732,49 @@ int plat_file_replace(const char *from, const char *to) {
return 1;
}
static char lock_held[4][1100];
static int lock_fd[4];
static int lock_n;
static PlatMutex lock_lock = PLAT_MUTEX_INIT;
int plat_lock_file(const char *path) {
plat_mutex_lock(&lock_lock);
int r = 1, nheld = lock_n;
for (int i = 0; i < nheld; i++)
if (!strcmp(lock_held[i], path)) goto done;
int fd = open(path, O_RDWR | O_CREAT | O_CLOEXEC, 0644); // open until plat_unlock_file or the process ends
if (fd < 0) {
r = -1;
goto done;
}
if (flock(fd, LOCK_EX | LOCK_NB)) {
r = errno == EWOULDBLOCK ? 0 : -1;
close(fd);
goto done;
}
if (nheld < 4) {
snprintf(lock_held[nheld], sizeof lock_held[0], "%s", path);
lock_fd[nheld] = fd;
lock_n = nheld + 1;
}
done:
plat_mutex_unlock(&lock_lock);
return r;
}
void plat_unlock_file(const char *path) {
plat_mutex_lock(&lock_lock);
for (int i = 0; i < lock_n; i++)
if (!strcmp(lock_held[i], path)) {
close(lock_fd[i]);
lock_n--;
memmove(&lock_held[i], &lock_held[i + 1], sizeof lock_held[0] * (size_t)(lock_n - i));
memmove(&lock_fd[i], &lock_fd[i + 1], sizeof lock_fd[0] * (size_t)(lock_n - i));
break;
}
plat_mutex_unlock(&lock_lock);
}
int plat_file_write_atomic(const char *path, const void *data, size_t n) {
// A rename replaces a read-only file here (only the folder's permission counts) but not on Windows: a file the
// player made read-only stays as it is on both.