Node.js Spawn:如何检查进程是否立即退出

时间:2017-08-01 17:20:14

标签: node.js asynchronous spawn process-management

在我的应用程序中,我需要生成一个调试器进程,给定一个转储文件进行调试,比如" example.dmp"。如果未找到转储文件,则它不是转储文件。该过程将成功生成,但会立即退出。我想在异步函数中抛出一条错误消息,可以稍后尝试捕获。

    const spawnDebuggerProcess = (debuggerConfigs) => {
        let debuggerProcess = spawn(config.debuggerName, debuggerConfigs)

        debuggerProcess.on('exit', (code, signal) => {
            console.log('pid ' + `${debuggerProcess.pid}`)
            console.log('child process exited with ' + `code ${code} and signal ${signal}`)
        })

        debuggerProcess.on('error', (error) => {})

        if (debuggerProcess.pid !== undefined) {
            return debuggerProcess
        }

        throw externalError.createError({
            name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
            description: 'Failed to spawn debugging process'
        })
    }

我的一个想法是在返回之前给这个功能一个时间窗口。如果进程在时间窗口之前退出,我应该抛出错误。但是因为node.js是异步的。我不知道如何实现这一点。谢谢!

====编辑=====

   const spawnDebuggerProcess = async (debuggerConfigs) => {
        let debuggerProcess = spawn(config.debuggerProcess.debuggerName, debuggerConfigs)

        /** added a flag */
        let exited = false

        debuggerProcess.on('exit', (code, signal) => {
            console.log('pid ' + `${debuggerProcess.pid}`)
            console.log('child process exited with ' + `code ${code} and signal ${signal}`)

            /** set flag to true if exited */
            exited = true
        })

        debuggerProcess.on('error', (error) => {})

        if (debuggerProcess.pid !== undefined) {

            /** delay this promise for a certain amount of time, act as the time window */
            await delay(config.debuggerProcess.immediateExitDelay)
            /** check the flag */
            if (exited) {
                throw externalError.createError({
                    name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
                    description: 'Process exited immediately'
                })
            }

            return debuggerProcess
        }

        throw externalError.createError({
            name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
            description: 'Failed to spawn debugging process'
        })
    }

这似乎有效,但我不确定这是不是一个好习惯。

0 个答案:

没有答案