import { readFile, writeFile, unlink } from "node:fs/promises";
import { getPidPath } from "./paths.js";
/**
 * Write the current process PID to the PID file.
 */
export async function writePidFile() {
    await writeFile(getPidPath(), String(process.pid), { mode: 0o644 });
}
/**
 * Read the PID from the PID file.
 * Returns null if the file does not exist or cannot be read.
 */
export async function readPidFile() {
    try {
        const content = await readFile(getPidPath(), "utf-8");
        const pid = parseInt(content.trim(), 10);
        return Number.isNaN(pid) ? null : pid;
    }
    catch {
        return null;
    }
}
/**
 * Remove the PID file.
 */
export async function removePidFile() {
    try {
        await unlink(getPidPath());
    }
    catch {
        // Ignore if file doesn't exist
    }
}
/**
 * Check if a process with the given PID is currently running.
 */
export function isProcessRunning(pid) {
    try {
        // Sending signal 0 checks for existence without killing
        process.kill(pid, 0);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Check if an existing daemon is already running.
 * Reads the PID file and checks if that process is alive.
 */
export async function checkExistingDaemon() {
    const pid = await readPidFile();
    if (pid === null)
        return false;
    return isProcessRunning(pid);
}
//# sourceMappingURL=pid.js.map