gpt4 book ai didi

node.js - 我如何在nodejs中监听和生成多个子进程

转载 作者:搜寻专家 更新时间:2023-10-31 23:38:02 26 4
gpt4 key购买 nike

我正在尝试在 for 循环中执行与 nodejs 中的子进程相同的 java jar 文件,但我该如何收听多个子输出???

test.jar 文件在无限循环中运行,它所做的只是递增并打印数字。

下面是我的代码,它确实在 nodejs 中生成了多个子进程,但它只打印了最后一个子进程的 pid,其他子进程的内容都添加到最后一个子进程。

var exec = require('child_process').exec, child;
var state = "java -jar " + "c://test.jar "
var exec = require('child_process').exec;

for (var i = 0; i < 10; i++) {

var child = exec(state);

// Add the child process to the list for tracking
p_list.push({process:child, content:""});

// Listen for any response:
child.stdout.on('data', function (data) {
console.log(child.pid, data);
p_list[i].content += data;
});

// Listen for any errors:
child.stderr.on('data', function (data) {
console.log(child.pid, data);
p_list[i].content += data;
});

// Listen if the process closed
child.on('close', function(exit_code) {
console.log('Closed before stop: Closing code: ', exit_code);
});
}

最佳答案

处理异步进程时需要关闭i

for (var i = 0; i < 10; i++) {
(function(i){
var child = exec(state);

// Add the child process to the list for tracking
p_list.push({process:child, content:""});

// Listen for any response:
child.stdout.on('data', function (data) {

console.log(child.pid, data);
p_list[i].content += data;
});

// Listen for any errors:
child.stderr.on('data', function (data) {
console.log(child.pid, data);
p_list[i].content += data;
});

// Listen if the process closed
child.on('close', function(exit_code) {
console.log('Closed before stop: Closing code: ', exit_code);
});
})(i)
}

关于node.js - 我如何在nodejs中监听和生成多个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32358845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com