背景
由于ons(阿里云 RocketMQ 包)基于 C艸 封裝而來,不支持單一進程內實例化多個生產者與消費者,為了解決這一問題,使用了 Node.js 子進程。
在使用的過程中碰到的坑
發布:進程管理關閉主進程后,子進程變為操作系統進程(pid 為 1)
幾種解決方案
將子進程看做獨立運行的進程,記錄 pid,發布時進程管理關閉主進程同時關閉子進程
主進程監聽關閉事件,主動關閉從屬于自己的子進程
子進程種類
子進程常用事件
close 與 exit 是有區別的,close 是在數據流關閉時觸發的事件,exit 是在子進程退出時觸發的事件。因為多個子進程可以共享同一個數據流,所以當某個子進程 exit 時不一定會觸發 close 事件,因為這個時候還存在其他子進程在使用數據流。
子進程數據流
因為是以主進程為出發點,所以子進程的數據流與常規理解的數據流方向相反,stdin:寫入流,stdout、stderr:讀取流。
spawn
spawn(command[, args][, options])
執行一條命令,通過 data 數據流返回各種執行結果。
基礎使用
const { spawn } = require('child_process');const child = spawn('find', [ '.', '-type', 'f' ]);child.stdout.on('data', (data) => { console.log(`child stdout:/n${data}`);});child.stderr.on('data', (data) => { console.error(`child stderr:/n${data}`);});child.on('exit', (code, signal) => { console.log(`child process exit with: code $[code], signal: ${signal}`);});常用參數
{ cwd: String, env: Object, stdio: Array | String, detached: Boolean, shell: Boolean, uid: Number, gid: Number}重點說明下 detached 屬性,detached 設置為 true 是為子進程獨立運行做準備。子進程的具體行為與操作系統相關,不同系統表現不同,Windows 系統子進程會擁有自己的控制臺窗口,POSIX 系統子進程會成為新進程組與會話負責人。
這個時候子進程還沒有完全獨立,子進程的運行結果會展示在主進程設置的數據流上,并且主進程退出會影響子進程運行。當 stdio 設置為 ignore 并調用 child.unref(); 子進程開始真正獨立運行,主進程可獨立退出。
exec
exec(command[, options][, callback])
執行一條命令,通過回調參數返回結果,指令未執行完時會緩存部分結果到系統內存。
const { exec } = require('child_process');exec('find . -type f | wc -l', (err, stdout, stderr) => { if (err) { console.error(`exec error: ${err}`); return; } console.log(`Number of files ${stdout}`);});兩全其美 ―― spawn 代替 exec
由于 exec 的結果是一次性返回,在返回前是緩存在內存中的,所以在執行的 shell 命令輸出過大時,使用 exec 執行命令的方式就無法按期望完成我們的工作,這個時候可以使用 spawn 代替 exec 執行 shell 命令。
const { spawn } = require('child_process');const child = spawn('find . -type f | wc -l', { stdio: 'inherit', shell: true});child.stdout.on('data', (data) => { console.log(`child stdout:/n${data}`);});child.stderr.on('data', (data) => { console.error(`child stderr:/n${data}`);});child.on('exit', (code, signal) => { console.log(`child process exit with: code $[code], signal: ${signal}`);});execFile
child_process.execFile(file[, args][, options][, callback])
執行一個文件
與 exec 功能基本相同,不同之處在于執行給定路徑的一個腳本文件,并且是直接創建一個新的進程,而不是創建一個 shell 環境再去運行腳本,相對更輕量級更高效。但是在 Windows 系統中如 .cmd 、 .bat 等文件無法直接運行,這是 execFile 就無法工作,可以使用 spawn、exec 代替。
fork
child_process.fork(modulePath[, args][, options])
執行一個 Node.js 文件
// parent.jsconst { fork } = require('child_process');const child = fork('child.js');child.on('message', (msg) => { console.log('Message from child', msg);});child.send({ hello: 'world' });// child.jsprocess.on('message', (msg) => { console.log('Message from parent:', msg);});let counter = 0;setInterval(() => { process.send({ counter: counter++ });}, 3000);fork 實際是 spawn 的一種特殊形式,固定 spawn Node.js 進程,并且在主子進程間建立了通信通道,讓主子進程可以使用 process 模塊基于事件進行通信。
子進程使用場景
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答