(lockPath: string)
| 7 | }; |
| 8 | |
| 9 | export 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, |
no test coverage detected