【问题标题】:Kill (like ctrl+c) exec (child process) on nodejs在nodejs上杀死(如ctrl + c)exec(子进程)
【发布时间】:2019-07-13 08:03:24
【问题描述】:

我在 index.js 中有以下代码:

var child = exec(
    'node app.js --board=' + data.data.board + ' --link=' + data.data.link,
    function (error, stdout, stderr) {
        if (error) console.log('exec error: ' + error)
        if (stderr) console.log('stderr: ' + stderr)
    }
)
.stdout.on('data', function(log_data) {
    console.log(log_data)
    socket.emit('listener', { ty: 'user_p_logs', num: data.num, log: log_data })
    fn(true)
})

这是run app.js 的代码,但我无法在index.js 上停止这个子进程

我在index.js中尝试了以下操作:

child.kill()
child.kill('SIGINT')
process.exit() // This stopped index.js, instead of its child.

更新:有答案吗?

【问题讨论】:

  • 你需要将进程分配给child,这样你才能杀死它。
  • 我该怎么做?

标签: javascript node.js exec child-process


【解决方案1】:

您分配给child 的是.stdout.on 的返回值,它是stdout 事件发射器,而不是child 进程。您需要它成为子进程。不要过度链接。 :-)

var child = exec(
    'node app.js --board=' + data.data.board + ' --link=' + data.data.link,
    function (error, stdout, stderr) {
        if (error) console.log('exec error: ' + error)
        if (stderr) console.log('stderr: ' + stderr)
    }
);
child.stdout.on('data', function(log_data) {
    console.log(log_data)
    socket.emit('listener', { ty: 'user_p_logs', num: data.num, log: log_data })
    fn(true)
});

那么,child.kill 应该可以工作了。

【讨论】:

  • 当我尝试你的答案时,我收到了这个错误'Cannot read property 'kill' of undefined'。
  • @User9123 - 那么你使用的exec不是child_process.exec,它清楚地记录了它返回一个ChildProcess object,它有一个kill方法。
  • 我正在使用这样的 child_process "const exec = require('child_process').exec"
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 2014-09-30
  • 2019-11-13
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
相关资源
最近更新 更多