MCPcopy Create free account
hub / github.com/clawbot7/cli-gateway / acquireProcessLock

Function acquireProcessLock

src/runtime/lock.ts:9–89  ·  view source on GitHub ↗
(lockPath: string)

Source from the content-addressed store, hash-verified

7};
8
9export function acquireProcessLock(lockPath: string): ProcessLock {
10 fs.mkdirSync(path.dirname(lockPath), { recursive: true });
11
12 try {
13 const fd = fs.openSync(lockPath, 'wx');
14 try {
15 fs.writeFileSync(
16 fd,
17 JSON.stringify(
18 {
19 pid: process.pid,
20 startedAt: Date.now(),
21 },
22 null,
23 2,
24 ) + '\n',
25 'utf8',
26 );
27 } finally {
28 fs.closeSync(fd);
29 }
30
31 return {
32 path: lockPath,
33 release: () => {
34 try {
35 fs.unlinkSync(lockPath);
36 } catch {
37 // ignore
38 }
39 },
40 };
41 } catch (err: any) {
42 if (err?.code !== 'EEXIST') throw err;
43
44 // If lock exists, verify the process is alive.
45 const existing = readLockFile(lockPath);
46 if (existing?.pid && isPidAlive(existing.pid)) {
47 throw new Error(`Another instance is running (pid=${existing.pid})`, {
48 cause: err,
49 });
50 }
51
52 // Stale lock.
53 try {
54 fs.unlinkSync(lockPath);
55 } catch {
56 // ignore
57 }
58
59 // Retry once.
60 const fd = fs.openSync(lockPath, 'wx');
61 try {
62 fs.writeFileSync(
63 fd,
64 JSON.stringify(
65 {
66 pid: process.pid,

Callers 2

lock.test.tsFile · 0.85
mainFunction · 0.85

Calls 2

readLockFileFunction · 0.85
isPidAliveFunction · 0.85

Tested by

no test coverage detected