2015-11-21 15 views
0

有沒有辦法讓哪些CPU執行子進程。我有8個CPU。所以父代碼啓動8個子進程。下面是節點代碼:確定正在使用進程的CPU nodejs

// 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); 

}); 

回答

0
從分叉雖然 child_process沒有 child對象

直接。

但是,您可以使用其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); 
+0

這將是一個很好的解決方案。不幸的是psr在Mac上不起作用。甚至在Linux上也無法找到它。 https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/ps.1.html – user603749

+0

你的問題是一個OSX的。我冒昧地編輯你的問題來添加標籤。在這種情況下,我想不出一個直接的解決方案,你可以嘗試使用'top'或'htop'。 – TMichel