Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 29 additions & 44 deletions src/pid-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,21 @@ export function getProcessInfo(
};
}

/**
* Builds the PidTrackResult returned when /proc/net/tcp cannot be read.
*
* Shared by trackPidForPort and trackPidForPortSync so the error shape
* lives in exactly one place.
*/
function makeTcpReadError(tcpPath: string, err: unknown): PidTrackResult {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Failed to read ${tcpPath}: ${err}`,
};
}

/**
* Resolves a PidTrackResult from already-read /proc/net/tcp content.
*
Expand Down Expand Up @@ -349,31 +364,16 @@ export async function trackPidForPort(
srcPort: number,
procPath = '/proc'
): Promise<PidTrackResult> {
try {
// Read /proc/net/tcp using async operations
const tcpPath = path.join(procPath, 'net', 'tcp');
let tcpContent: string;

try {
tcpContent = await fsPromises.readFile(tcpPath, 'utf-8');
} catch (err) {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Failed to read ${tcpPath}: ${err}`,
};
}
const tcpPath = path.join(procPath, 'net', 'tcp');
let tcpContent: string;

return resolvePidFromTcpContent(tcpContent, srcPort, procPath);
try {
tcpContent = await fsPromises.readFile(tcpPath, 'utf-8');
} catch (err) {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Unexpected error: ${err}`,
};
return makeTcpReadError(tcpPath, err);
}

return resolvePidFromTcpContent(tcpContent, srcPort, procPath);
}

/**
Expand All @@ -384,31 +384,16 @@ export async function trackPidForPort(
* @returns PidTrackResult with process information
*/
export function trackPidForPortSync(srcPort: number, procPath = '/proc'): PidTrackResult {
try {
// Read /proc/net/tcp
const tcpPath = path.join(procPath, 'net', 'tcp');
let tcpContent: string;

try {
tcpContent = fs.readFileSync(tcpPath, 'utf-8');
} catch (err) {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Failed to read ${tcpPath}: ${err}`,
};
}
const tcpPath = path.join(procPath, 'net', 'tcp');
let tcpContent: string;

return resolvePidFromTcpContent(tcpContent, srcPort, procPath);
try {
tcpContent = fs.readFileSync(tcpPath, 'utf-8');
} catch (err) {
return {
pid: -1,
cmdline: 'unknown',
comm: 'unknown',
error: `Unexpected error: ${err}`,
};
return makeTcpReadError(tcpPath, err);
}

return resolvePidFromTcpContent(tcpContent, srcPort, procPath);
}

/**
Expand Down
Loading