子节点中存在节点生成过程和句柄

时间:2018-08-27 19:31:24

标签: node.js process child-process spawn

我想要生一个孩子,在5秒后我想杀死这个孩子。在孩子中,我想在退出前打印再见。

我的代码不起作用,再见未打印,为什么?

父母:

const child = require('child_process').spawn('node', ['index.js']);

child.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
});

child.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

child.on('exit', function (code, signal) {
    console.log('child process exited with ' +
        `code ${code} and signal ${signal}`);
});

setTimeout(() => {
    child.kill('SIGINT');
}, 5000)

孩子

const handleAppExit = () => {
    process.stdin.resume()//so the program will not close instantly

    const exitHandler = (options, err) => {
        console.log('bye bye') 
        process.exit()
    }

    // do something when app is closing
    process.on('exit', exitHandler.bind(null, { cleanup: true, }))

    //catches ctrl+c event
    process.on('SIGINT', exitHandler.bind(null, { exit: true }))

    process.on('SIGTERM', exitHandler.bind(null, { cleanup: true, exit: true }))

    // catches "kill pid" (for example: nodemon restart)
    process.on('SIGUSR1', exitHandler.bind(null, { exit: true }))
    process.on('SIGUSR2', exitHandler.bind(null, { exit: true }))

    //catches uncaught exceptions
    process.on('uncaughtException', exitHandler.bind(null, { exit: true }))
}

handleAppExit()
// some other async code - require('http').createServer(require('express')()) ...

因此,当我使用节点index.js手动运行该子级并且在启动后按ctrl c时,将打印bye bye。为什么不使用子组合?

谢谢您的帮助。

0 个答案:

没有答案