Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

Fix duplicate app instances

Etienne Lescot779045381e04
diff --git a/electron/main.ts b/electron/main.ts
index 57e489f30..c2d7a4d48 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -19,6 +19,7 @@ import {
} from "./globalShortcut";
import { mainT, setMainLocale } from "./i18n";
import { getSelectedDesktopSource, registerIpcHandlers } from "./ipc/handlers";
+import { acquireStableInstanceLock } from "./singleInstanceLock";
import {
createCountdownOverlayWindow,
createEditorWindow,
@@ -112,13 +113,16 @@ function showMainWindow() {
createWindow();
}
-const hasSingleInstanceLock = app.requestSingleInstanceLock();
+const stableInstanceLock = acquireStableInstanceLock();
+const hasElectronSingleInstanceLock = app.requestSingleInstanceLock();
+const hasSingleInstanceLock = Boolean(stableInstanceLock && hasElectronSingleInstanceLock);
if (hasSingleInstanceLock) {
app.on("second-instance", () => {
showMainWindow();
});
} else {
+ stableInstanceLock?.release();
app.quit();
}
@@ -468,6 +472,7 @@ app.on("activate", () => {
app.on("will-quit", () => {
unregisterAllGlobalShortcuts();
+ stableInstanceLock?.release();
});
const appReady = hasSingleInstanceLock ? app.whenReady() : null;
diff --git a/electron/singleInstanceLock.test.ts b/electron/singleInstanceLock.test.ts
new file mode 100644
index 000000000..4df35c72b
--- /dev/null
+++ b/electron/singleInstanceLock.test.ts
@@ -0,0 +1,52 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { acquireStableInstanceLock } from "./singleInstanceLock";
+
+const testDirs: string[] = [];
+
+function createTestLockDir() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "openscreen-lock-test-"));
+ testDirs.push(dir);
+ return path.join(dir, "app.lock");
+}
+
+afterEach(() => {
+ for (const dir of testDirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+describe("acquireStableInstanceLock", () => {
+ it("prevents a second lock while the owning process is still running", () => {
+ const lockDir = createTestLockDir();
+ const firstLock = acquireStableInstanceLock({ lockDir });
+
+ expect(firstLock).not.toBeNull();
+ expect(acquireStableInstanceLock({ lockDir })).toBeNull();
+
+ firstLock?.release();
+ });
+
+ it("reclaims a stale lock when its process is gone", () => {
+ const lockDir = createTestLockDir();
+ fs.mkdirSync(lockDir);
+ fs.writeFileSync(path.join(lockDir, "pid"), "99999999\n");
+
+ const lock = acquireStableInstanceLock({ lockDir });
+
+ expect(lock).not.toBeNull();
+ expect(fs.readFileSync(path.join(lockDir, "pid"), "utf8")).toBe(`${process.pid}\n`);
+
+ lock?.release();
+ });
+
+ it("does not remove a fresh empty lock directory", () => {
+ const lockDir = createTestLockDir();
+ fs.mkdirSync(lockDir);
+
+ expect(acquireStableInstanceLock({ lockDir })).toBeNull();
+ expect(fs.existsSync(lockDir)).toBe(true);
+ });
+});
diff --git a/electron/singleInstanceLock.ts b/electron/singleInstanceLock.ts
new file mode 100644
index 000000000..d1a0a01af
--- /dev/null
+++ b/electron/singleInstanceLock.ts
@@ -0,0 +1,104 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const LOCK_DIR_PREFIX = "openscreen-single-instance";
+const PID_FILE_NAME = "pid";
+const EMPTY_LOCK_STALE_MS = 30_000;
+
+export type StableInstanceLock = {
+ lockDir: string;
+ release: () => void;
+};
+
+type LockOptions = {
+ lockDir?: string;
+ pid?: number;
+ now?: () => number;
+};
+
+function isProcessRunning(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+function readLockPid(lockDir: string): number | null {
+ try {
+ const rawPid = fs.readFileSync(path.join(lockDir, PID_FILE_NAME), "utf8").trim();
+ const pid = Number(rawPid);
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
+ } catch {
+ return null;
+ }
+}
+
+function isEmptyLockStale(lockDir: string, now: () => number): boolean {
+ try {
+ const stat = fs.statSync(lockDir);
+ return now() - stat.mtimeMs > EMPTY_LOCK_STALE_MS;
+ } catch {
+ return false;
+ }
+}
+
+function releaseLock(lockDir: string, pid: number) {
+ if (readLockPid(lockDir) !== pid) {
+ return;
+ }
+ fs.rmSync(lockDir, { recursive: true, force: true });
+}
+
+function getCurrentUserLockKey() {
+ if (typeof process.getuid === "function") {
+ return `uid-${process.getuid()}`;
+ }
+
+ try {
+ const username = os.userInfo().username.replace(/[^a-zA-Z0-9._-]/g, "_");
+ return username || "default";
+ } catch {
+ return "default";
+ }
+}
+
+export function getStableInstanceLockDir() {
+ return path.join(os.tmpdir(), `${LOCK_DIR_PREFIX}-${getCurrentUserLockKey()}.lock`);
+}
+
+export function acquireStableInstanceLock(options: LockOptions = {}): StableInstanceLock | null {
+ const lockDir = options.lockDir ?? getStableInstanceLockDir();
+ const pid = options.pid ?? process.pid;
+ const now = options.now ?? Date.now;
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ try {
+ fs.mkdirSync(lockDir, { mode: 0o700 });
+ fs.writeFileSync(path.join(lockDir, PID_FILE_NAME), `${pid}\n`, { flag: "wx" });
+ return {
+ lockDir,
+ release: () => releaseLock(lockDir, pid),
+ };
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "EEXIST") {
+ throw error;
+ }
+
+ const existingPid = readLockPid(lockDir);
+ if (existingPid && isProcessRunning(existingPid)) {
+ return null;
+ }
+ if (!existingPid && !isEmptyLockStale(lockDir, now)) {
+ return null;
+ }
+
+ fs.rmSync(lockDir, { recursive: true, force: true });
+ }
+ }
+
+ return null;
+}