image.png
node子進程里有4個方法郁竟,
- exec 主要用來執(zhí)行一個shell方法,其內(nèi)部還是調(diào)用了spawn ,不過他有最大緩存限制。
- execFile 同上。
- fork 這個用的比較多浊仆,子進程可以和父進程進行IPC通訊。
記住豫领,衍生的 Node.js 子進程獨立于父進程抡柿,但兩者之間建立的 IPC 通信通道除外。 每個進程都有自己的內(nèi)存等恐,帶有自己的 V8 實例
parent.js
const {fork} = require('child_process');
for(let i = 0; i < 3; i++){
const p = fork('./child.js', [JSON.stringify({id:1,name:1})]);
p.on('message', (msg) => {
console.log(`messsgae from child msg=${JSON.stringify(msg)}`, );
});
p.send({hello:`來自爸爸${process.pid} 進程id=${i}的問候`});
}
child.js
const t = JSON.parse(process.argv[2]);
console.error(`子進程 t=${JSON.stringify(t)}`);
process.send({hello:`兒子pid=${process.pid} 給爸爸進程pid=${process.ppid} 請安`});
process.on('message', (msg)=>{
console.error(`子進程 msg=${JSON.stringify(msg)}`);
});
輸出結(jié)果:
image.png
- spawn 這個比較原生洲劣。上面3個底層都是調(diào)用這個spawn.