因爲 ons(阿里雲 RocketMQ 包)基於 C艹 封裝而來,不支持單一進程內實例化多個生產者與消費者,爲了解決這一問題,使用了 Node.js 子進程。前端
在使用的過程當中碰到的坑shell
幾種解決方案npm
close 與 exit 是有區別的,close 是在數據流關閉時觸發的事件,exit 是在子進程退出時觸發的事件。由於多個子進程能夠共享同一個數據流,因此當某個子進程 exit 時不必定會觸發 close 事件,由於這個時候還存在其餘子進程在使用數據流。緩存
由於是以主進程爲出發點,因此子進程的數據流與常規理解的數據流方向相反,stdin:寫入流,stdout、stderr:讀取流。bash
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 系統子進程會成爲新進程組與會話負責人。ui
這個時候子進程尚未徹底獨立,子進程的運行結果會展現在主進程設置的數據流上,而且主進程退出會影響子進程運行。當 stdio 設置爲 ignore
並調用 child.unref();
子進程開始真正獨立運行,主進程可獨立退出。阿里雲
exec(command[, options][, callback])spa
執行一條命令,經過回調參數返回結果,指令未執行完時會緩存部分結果到系統內存。
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}`);
});
複製代碼
因爲 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}`);
});
複製代碼
child_process.execFile(file[, args][, options][, callback])
執行一個文件
與 exec 功能基本相同,不一樣之處在於執行給定路徑的一個腳本文件,而且是直接建立一個新的進程,而不是建立一個 shell 環境再去運行腳本,相對更輕量級更高效。可是在 Windows 系統中如 .cmd
、.bat
等文件沒法直接運行,這是 execFile 就沒法工做,可使用 spawn、exec 代替。
child_process.fork(modulePath[, args][, options])
執行一個 Node.js 文件
// parent.js
const { fork } = require('child_process');
const child = fork('child.js');
child.on('message', (msg) => {
console.log('Message from child', msg);
});
child.send({ hello: 'world' });
複製代碼
// child.js
process.on('message', (msg) => {
console.log('Message from parent:', msg);
});
let counter = 0;
setInterval(() => {
process.send({ counter: counter++ });
}, 3000);
複製代碼
fork 實際是 spawn 的一種特殊形式,固定 spawn Node.js 進程,而且在主子進程間創建了通訊通道,讓主子進程可使用 process 模塊基於事件進行通訊。
const commander = require('commander');
const path = require('path');
const start = require('./lib/start');
commander
.command('start <entry>')
.description('start process')
.option('--dev', 'set dev environment')
.action(function(entry, options) {
start({
entry: path.resolve(__dirname, `../entry/${entry}`),
isDaemon: !options.dev
});
});
複製代碼
true
,調用 child.unref();
使子進程獨立運行const { spawn } = require('child_process');
const child = spawn(process.execPath, [ path.resolve(__dirname, 'cluster') ], {
cwd: path.resolve(__dirname, '../../'),
env: Object.assign({}, process.env, {
izayoiCoffee: JSON.stringify({
configDir: config.akyuuConfigDir,
entry: options.entry
})
}),
detached: true,
stdio: 'ignore'
});
child.on('exit', function(code, signal) {
console.error(`start process \`${path.basename(options.entry)}\` failed, ` +
`code: ${code}, signal: ${signal}`);
process.exit(1);
});
child.unref();
複製代碼
child
.on('fork', function(worker) {
try {
fs.writeFileSync(
'pid file path',
worker.process.pid,
{ encoding: 'utf8' }
);
} catch(err) {
console.error(
'[%s] [uncaughtException] [master: %d] \n%s',
moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss.SSS'),
process.pid,
err.stack
);
}
})
.on('exit', function(worker, code, signal) {
try {
fs.unlinkSync('pid file path');
} catch(err) {
console.error(
'[%s] [uncaughtException] [master: %d] \n%s',
moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss.SSS'),
process.pid,
err.stack
);
}
});
複製代碼
const { fork } = require('child_process); const child = fork('some child process file'); // 程序中止信號 process.on('SIGHUP', function() { child.kill('SIGHUP'); process.exit(0); }); // kill 默認參數信號 process.on('SIGTERM', function() { child.kill('SIGHUP'); process.exit(0); }); // Ctrl + c 信號 process.on('SIGINT', function() { child.kill('SIGHUP'); process.exit(0); }); // 退出事件 process.on('exit', function() { child.kill('SIGHUP'); process.exit(0); }); // 未捕獲異常 process.on('uncaughtException', function() { child.kill('SIGHUP'); process.exit(0); }); 複製代碼
在使用 Node.js 作開發中,尤爲是 API 開發過程當中不多涉及到子進程,可是子進程仍是比較重要的一個組成部分。Node.js 能夠利用子進程作些計算密集型任務,雖然沒有 C艹 等其餘語言高效、方便,可是也不失爲一種方案,在沒有掌握其餘語言時能夠用 Node.js 支撐起業務場景。對於子進程的採坑與使用在本文中記錄,以供將來的本身參考。