Node.js 多进程

2018-12-04  本文已影响10人  最帅的坏兔子

support.js

console.log('进程' + process.argv[2] + '执行。');

master.js

const fs = require('fs');
const child_process = require('child_process');
for(var i=0; i<3; i++){
    var workerProcess = child_process.exec('node support.js '+i, function(error, stdout, stderr){
        if (error) {
            console.log(error.stack);
            console.log('Error code: '+ error.code);
            console.log('Signal received: '+ error.signal);
        }
        console.log('stdout: '+ stdout);
        console.log('stderr: '+ stderr);
    });
    workerProcess.on('exit', function(code){
        console.log('子进程已退出,退出码 ' + code);
    });
}
exec() 方法.png

master.js

const fs = require('fs');
const child_process = require('child_process');
for(var i=0; i<3; i++){
    var workerProcess = child_process.spawn('node', ['support.js', i]);
    workerProcess.stdout.on('data', function(data){
        console.log('stdout' + data);
    });
    workerProcess.stderr.on('data', function(data){
        console.log('stderr' + data);
    });
    workerProcess.on('close', function(code){
        console.log('子进程已退出,退出码 ' + code);
    });
}
spawn() 方法.png

master.js

const fs = require('fs');
const child_process = require('child_process');
for(var i=0; i<3; i++){
    var workerProcess = child_process.fork('support.js', [i]);
    workerProcess.on('close', function(code){
        console.log('子进程已退出,退出码 ' + code);
    });
}
fork() 方法.png
上一篇下一篇

猜你喜欢

热点阅读