Reputation: 5980
I'm using this node script as a "runner" for my project (need to start/stop three scripts at the same time). Now I wonder if the child_process's spawn from inside a node process will or won't use multi cores that my server would have (I'm 90% confident on a YES, but better safe than sorry).
var CP = require("child_process")
, children = [ 'server1', 'server2', 'server3' ]
, child
children.forEach(function(name) {
child = CP.spawn("node", [name] )
child.stdout.on('data', function (data) {
process.stdout.write(data.toString());
})
child.stderr.on('data', function (data) {
process.stdout.write(data.toString());
})
}
});
OS is Ubuntu Linux.
Upvotes: 6
Views: 1402
Reputation: 6108
Yup. spawn()
creates completely new processes on the OS-level.
And you could even simplify it a bit by using pipe()
:
var spawn = require("child_process").spawn
, children = [ 'server1', 'server2', 'server3' ]
, child
children.forEach(function(name) {
child = spawn("node", [name] )
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
// Catch errors (dies quite hard on first child with non-zero exit code...)
child.on('exit', function (code) {
if(code !== 0) {
process.exit(code);
}
});
});
(Also added listener on exit
, so it'll at least propagate errors in some way. If it's something you want to do, you may want to keep track of them until the last process has finished, and then call process.exit()
with the largest or smallest code...)
Upvotes: 7
Reputation: 651
This will absolutely utilize multiple cores. Node won't, and never should, bind a child process to a specific CPU or CPU core.
Upvotes: 0