我试图在for循环中的nodejs中执行与java进程相同的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);
});
}
答案 0 :(得分:4)
在处理异步进程时,您需要关闭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)
}
答案 1 :(得分:1)
您可以尝试查看Node {JS的Cluster API。基本上它允许你有一个主流程来旋转工人,然后每个工人都是它自己的流程。我认为你需要的是什么?