判断CPU in use a process nodejs
Determine the CPU in use of a process nodejs
有没有办法获取哪些 CPU 正在执行子进程。我有 8 个 CPU。所以父代码启动了8个子进程。这是节点代码:
// parent.js
var child_process = require('child_process');
var numchild = require('os').cpus().length;
var done = 0;
for (var i = 0; i < numchild; i++){
var child = child_process.fork('./child');
child.send((i + 1) * 1000);
child.on('message', function(message) {
console.log('[parent] received message from child:', message);
done++;
if (done === numchild) {
console.log('[parent] received all results');
}
});
}
// child.js
process.on('message', function(message) {
console.log('[child] received message from server:', message);
setTimeout(function() {
process.send({
child : process.pid,
result : message + 1
});
process.disconnect();
}, 10000);
});
直接来自 child
对象,虽然 child_process
没有。
但是您可以使用其 PID
- child.pid
- 并从节点执行例如 UNIX ps -p <PID> -o psr
命令来解析其响应。 PSR
是在特定进程中使用的处理器数。
为此,您可以根据需要调整 node.js shell command execution 中建议的解决方案:
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
child.stdout.on('data', function (data) { cb_stdout(me, data) });
child.stdout.on('end', function () { cb_end(me) });
}
foo = new cmd_exec('netstat', ['-rn'],
function (me, data) {me.stdout += data.toString();},
function (me) {me.exit = 1;}
);
function log_console() {
console.log(foo.stdout);
}
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
有没有办法获取哪些 CPU 正在执行子进程。我有 8 个 CPU。所以父代码启动了8个子进程。这是节点代码:
// parent.js
var child_process = require('child_process');
var numchild = require('os').cpus().length;
var done = 0;
for (var i = 0; i < numchild; i++){
var child = child_process.fork('./child');
child.send((i + 1) * 1000);
child.on('message', function(message) {
console.log('[parent] received message from child:', message);
done++;
if (done === numchild) {
console.log('[parent] received all results');
}
});
}
// child.js
process.on('message', function(message) {
console.log('[child] received message from server:', message);
setTimeout(function() {
process.send({
child : process.pid,
result : message + 1
});
process.disconnect();
}, 10000);
});
直接来自 child
对象,虽然 child_process
没有。
但是您可以使用其 PID
- child.pid
- 并从节点执行例如 UNIX ps -p <PID> -o psr
命令来解析其响应。 PSR
是在特定进程中使用的处理器数。
为此,您可以根据需要调整 node.js shell command execution 中建议的解决方案:
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
child.stdout.on('data', function (data) { cb_stdout(me, data) });
child.stdout.on('end', function () { cb_end(me) });
}
foo = new cmd_exec('netstat', ['-rn'],
function (me, data) {me.stdout += data.toString();},
function (me) {me.exit = 1;}
);
function log_console() {
console.log(foo.stdout);
}
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);