🌳
pt0/serverF/killPidOnPortAI.mts
1import { execSync } from 'child_process'
3import { cliFlag } from './cliArgAI.mts'
4import { sleep } from '../sharedF/sleepF.mts'
6export const killExistingKey = 'killExisting' as const
7export const killExistingCliSchema = {[killExistingKey]: {flag: true, desc: 'kill existing process on port'}} as const
9export const maybeKillExisting = async (portNo: number) => {
10 if (cliFlag(killExistingKey)) await killPidOnPort(portNo)
13export const killPidOnPort = async (portNo: number) => {
14 try {
15 const lsofOutput = execSync(`lsof -ti :${portNo}`, { encoding: 'utf8' }).trim()
16 if (!lsofOutput) return
18 const pidA = lsofOutput.split('\n').map(s => parseInt(s, 10)).filter(Boolean)
19 for (const pid of pidA) {
20 betLog('killPidOnPortAI killing', { pid, portNo })
21 process.kill(pid, 'SIGTERM')
22 }
24 // Give the process a moment to exit gracefully
25 await sleep(500)
26 } catch {
27 // lsof returns non-zero if no process found, which is fine
28 }