import { unlinkSync as unlink } from 'fs' ; import once from 'lodash/once' ; import { Logger } from '../logging' ; import { writeFile , exists } from './fs' ; import { PidConfigType } from './pid_config' ; export const writePidFile = async ( { pidConfig , logger , } ) => { const path = pidConfig . file ; if ( ! path ) { return ; } const pid = String ( process . pid ) ; if ( await exists ( path ) ) { const message = `pid file already exists at ${ path }` ; if ( pidConfig . exclusive ) { throw new Error ( message ) ; } else { logger . warn ( message , { path , pid } ) ; } } await writeFile ( path , pid ) ; logger . debug ( `wrote pid file to ${ path }` , { path , pid } ) ; const clean = once ( ( ) => { unlink ( path ) ; } ) ; process . once ( 'exit' , clean ) ; process . once ( 'SIGINT' , ( ) => { clean ( ) ; process . kill ( process . pid , 'SIGINT' ) ; } ) ; } ;