Node.js 多进程
核对 Node.js child_process(exec、execFile、spawn、fork)参数与流/IPC 差异、cluster 多核模型与优雅重启思路,以及基于 fork 进程池卸载 HTTP 计算任务的本地实测。
学完这一章,你能够
- 核对 Node.js child_process(exec、execFile、spawn、fork)参数与流/IPC 差异、cluster 多核模型与优雅重启思路,以及基于 fork 进程池卸载 HTTP 计算任务的本地实测。
多进程模型与 exec() / execFile() 缓冲执行
Node.js 主事件循环以单线程事件驱动处理 I/O 并发,但在多核 CPU 环境下可借助 `node:child_process` 与 `node:cluster` 创建多个子进程以横向利用算力。每个子进程都具备 `child.stdin`、`child.stdout` 与 `child.stderr` 三个标准流(可继承父进程或独立管道)。`child_process` 提供四个常用入口:`exec` 通过 Shell 执行命令并缓冲完整输出回传回调;`execFile` 直接执行可执行文件而不经过 Shell,能降低命令注入风险;`spawn` 按参数数组启动新进程并以流方式实时返回数据;`fork` 是 `spawn` 的特化形式,专门运行 Node.js 模块并内建父子进程 IPC 通信信道。`cluster` 模块则支持多工作进程共享同一监听端口以实现一核一进程 Web 服务,工程上也可结合反向代理 + 多实例或用 `worker_threads` 承载纯 CPU 密集计算。
`child_process.exec(command[, options], callback)` 接收空格分隔的命令字符串、可选配置对象与 `(error, stdout, stderr)` 回调。常用配置包括:`cwd`(工作目录)、`env`(环境变量对象)、`encoding`(默认 `'utf8'`)、`shell`(UNIX 默认 `/bin/sh` 配 `-c`,Windows 默认 `cmd.exe` 配 `/s /c`)、`timeout`(超时毫秒,默认 `0`)、`maxBuffer`(stdout/stderr 允许的最大字节缓冲,早期版本默认 `200*1024`,现代 Node.js 已提升至 `1024*1024`,超限将终止子进程)、`killSignal`(默认 `'SIGTERM'`)以及类 UNIX 平台的 `uid` / `gid`。由于 `exec` 会等待子进程结束并将输出整体装入内存缓冲,适合输出体量小的命令。
并发调用 3 次 `exec` 运行 `support` 脚本传入参数 `0`、`1`、`2` 时,三个子进程由操作系统并行调度,完成先后顺序并不固定;通常子进程退出先触发 `exit` 事件,待其 `stdio` 流关闭后再触发 `exec` 回调。本站 Node.js v24.22.3 本地实测并行启动 3 个 `exec` 子进程均以退出码 `0` 完成,排序后精确收集到 `["进程 0 执行。","进程 1 执行。","进程 2 执行。"]`,同时 `execFile(process.execPath, [supportPath, 'safe'])` 绕过 Shell 直接返回 `进程 safe 执行。`。
spawn() 流式接口与 fork() 内建 IPC 通道
`child_process.spawn(command[, args][, options])` 直接接收命令名与字符串参数数组 `args`,常用选项包括 `cwd`、`env`、`stdio`(配置标准流继承或管道)、`detached`(脱离父进程成为新进程组组长)以及 `uid`/`gid`。与 `exec` 不同,`spawn` 不设总缓冲上限,进程一启动便通过 `stdout`/`stderr` 可读流持续吐出数据块并在流关闭后触发 `close` 事件,适合大体积输出或长生命周期任务。本站实测 3 个 `spawn` 子进程全部以状态码 `0` 结束、`stderr` 为空,流式汇总得到 3 条预期输出。
`child_process.fork(modulePath[, args][, options])` 专用于启动独立的 Node.js 模块子进程,除支持 `cwd`、`env`、`uid`、`gid` 外,还提供 `execPath`(指定 Node 可执行文件路径)、`execArgv`(传给 Node 解释器的参数,默认继承 `process.execArgv`)与 `silent`(设为 `true` 时将子进程 `stdin`/`stdout`/`stderr` 管道化到父进程,默认 `false` 直接继承)。其最大优势在于自动建立父子进程 IPC 通道,可通过 `send()` 与 `message` 事件收发结构化消息。本站实测以 `silent: true` 派生 worker 子进程并通过 IPC 发送 `n=20` 斐波那契任务,子进程在独立 PID 下算得 `6765` 回传并在收到关闭指令后以退出码 `0` 退出。
cluster 多核服务、优雅重启与自建进程池
使用 `node:cluster` 时,主进程(`cluster.isPrimary`)按 CPU 核心数调用 `cluster.fork()` 启动多个工作进程,并监听 `exit` 事件自动拉起异常退出的 worker;各工作进程共同监听同一 HTTP 端口分摊请求,线上多实例亦可前置 Nginx、Envoy 或 Kubernetes Service 负载均衡,涉及 WebSocket 或粘性会话时需采用四层源地址哈希或应用层路由粘滞。零停机优雅重启的核心流程是:主进程收到重载信号(如类 UNIX 的 `SIGUSR2`,Windows 无该信号需改为 HTTP/RPC 管理接口触发)后,先派生新 worker 并等待其进入 `listening` 状态,再对旧 worker 调用 `disconnect()` 令其处理完在途请求后退出,超时则兜底终止。
面对高频独立的重计算任务(如批量压缩、加密或解析),每次请求都临时 `fork`/`spawn` 开销过高,工程上应构建固定规模的进程池(Process Pool):将任务封装为 IPC 消息入队,由池控制器分配给空闲 worker 并在完成后回收复用,生产环境还需补齐超时、重试、幂等与队列长度背压保护。本站实测搭建容量为 `2` 的 `MiniProcessPool` 并配合本地 HTTP 接口 `/fib?n=20`:6 个并发任务 `[10,12,15,18,20,21]` 精确返回 `[55,144,610,2584,6765,10946]` 且全部复用不超过 2 个 worker PID,HTTP 接口返回 `200` 与 `{"n":20,"result":6765}` 而未阻塞主线程。
运行 child_process exec/execFile/spawn/fork IPC 与 HTTP 进程池卸载实验
展开查看收起
import { exec, execFile, spawn, fork } from 'node:child_process';
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function runExec(cmd) {
return new Promise((resolve, reject) => {
let exitCode = null;
const child = exec(cmd, { encoding: 'utf8' }, (err, stdout, stderr) => {
if (err) return reject(err);
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), exitCode });
});
child.on('exit', (code) => {
exitCode = code;
});
});
}
function runExecFile(bin, args) {
return new Promise((resolve, reject) => {
execFile(bin, args, { encoding: 'utf8' }, (err, stdout, stderr) => {
if (err) return reject(err);
resolve({ stdout: stdout.trim(), stderr: stderr.trim() });
});
});
}
function runSpawn(bin, args) {
return new Promise((resolve, reject) => {
const child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] });
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (d) => {
stdout += d;
});
child.stderr.on('data', (d) => {
stderr += d;
});
child.on('error', reject);
child.on('close', (code) => {
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code });
});
});
}
class MiniProcessPool {
constructor(workerFile, size) {
this.workerFile = workerFile;
this.idle = [];
this.all = [];
this.queue = [];
this.pending = new Map();
this.seq = 0;
for (let i = 0; i < size; i++) {
const w = fork(workerFile, [], { silent: true });
w.on('message', (msg) => {
if (msg?.type === 'done') {
const entry = this.pending.get(msg.id);
if (entry) {
this.pending.delete(msg.id);
entry.resolve({ result: msg.result, pid: msg.pid });
}
this.idle.push(w);
this._drain();
}
});
this.idle.push(w);
this.all.push(w);
}
}
_drain() {
while (this.queue.length > 0 && this.idle.length > 0) {
const task = this.queue.shift();
const w = this.idle.shift();
this.pending.set(task.id, task);
w.send({ type: 'task', id: task.id, n: task.n });
}
}
runTask(n) {
const id = `t${++this.seq}`;
return new Promise((resolve, reject) => {
this.queue.push({ id, n, resolve, reject });
this._drain();
});
}
async close() {
await Promise.all(
this.all.map(
(w) =>
new Promise((resolve) => {
if (w.exitCode !== null) return resolve();
w.once('exit', () => resolve());
w.send({ type: 'shutdown' });
}),
),
);
}
}
async function main() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-proc-'));
const supportPath = path.join(tmpDir, 'support.mjs');
const workerPath = path.join(tmpDir, 'worker.mjs');
await fs.writeFile(
supportPath,
'console.log("进程 " + process.argv[2] + " 执行。");\n',
'utf8',
);
await fs.writeFile(
workerPath,
[
'function fib(n) { return n <= 1 ? n : fib(n - 1) + fib(n - 2); }',
'process.on("message", (msg) => {',
' if (msg.type === "task") {',
' process.send({ type: "done", id: msg.id, result: fib(msg.n), pid: process.pid });',
' } else if (msg.type === "shutdown") {',
' process.exit(0);',
' }',
'});',
].join('\n'),
'utf8',
);
const cases = [];
try {
// Case 1: child_process_exec_and_execfile
const execResults = await Promise.all(
[0, 1, 2].map((i) => runExec(`"${process.execPath}" "${supportPath}" ${i}`)),
);
const execFileRes = await runExecFile(process.execPath, [supportPath, 'safe']);
const actual1 = {
execOutputs: execResults.map((r) => r.stdout).sort(),
execCodes: execResults.map((r) => r.exitCode),
execFileStdout: execFileRes.stdout,
};
const expected1 = {
execOutputs: ['进程 0 执行。', '进程 1 执行。', '进程 2 执行。'],
execCodes: [0, 0, 0],
execFileStdout: '进程 safe 执行。',
};
cases.push({
name: 'child_process_exec_and_execfile',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: child_process_spawn_streams
const spawnResults = await Promise.all(
[0, 1, 2].map((i) => runSpawn(process.execPath, [supportPath, String(i)])),
);
const actual2 = {
outputs: spawnResults.map((r) => r.stdout).sort(),
codes: spawnResults.map((r) => r.code),
stderrEmpty: spawnResults.every((r) => r.stderr === ''),
};
const expected2 = {
outputs: ['进程 0 执行。', '进程 1 执行。', '进程 2 执行。'],
codes: [0, 0, 0],
stderrEmpty: true,
};
cases.push({
name: 'child_process_spawn_streams',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: child_process_fork_ipc
const ipcResult = await new Promise((resolve, reject) => {
const child = fork(workerPath, ['w1'], { silent: true });
let reply = null;
child.on('error', reject);
child.on('message', (msg) => {
reply = msg;
child.send({ type: 'shutdown' });
});
child.on('close', (code) => {
resolve({
id: reply?.id,
result: reply?.result,
distinctPid: typeof reply?.pid === 'number' && reply.pid !== process.pid,
exitCode: code,
});
});
child.send({ type: 'task', id: 't1', n: 20 });
});
const expected3 = { id: 't1', result: 6765, distinctPid: true, exitCode: 0 };
cases.push({
name: 'child_process_fork_ipc',
passed: JSON.stringify(ipcResult) === JSON.stringify(expected3),
expected: expected3,
actual: ipcResult,
});
// Case 4: process_pool_reuse_and_http_offload
const pool = new MiniProcessPool(workerPath, 2);
const server = http.createServer(async (req, res) => {
const url = new URL(req.url || '/', 'http://127.0.0.1');
if (url.pathname === '/fib') {
const n = Number(url.searchParams.get('n') || 10);
const { result } = await pool.runTask(n);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ n, result }));
return;
}
res.writeHead(404).end('Not Found');
});
try {
const batchInputs = [10, 12, 15, 18, 20, 21];
const batchOut = await Promise.all(batchInputs.map((n) => pool.runTask(n)));
const workerPids = new Set(batchOut.map((o) => o.pid));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const httpRes = await fetch(`http://127.0.0.1:${port}/fib?n=20`);
const httpJson = await httpRes.json();
const actual4 = {
results: batchOut.map((o) => o.result),
reusedWithinPoolSize: workerPids.size >= 1 && workerPids.size <= 2,
httpStatus: httpRes.status,
httpBody: httpJson,
};
const expected4 = {
results: [55, 144, 610, 2584, 6765, 10946],
reusedWithinPoolSize: true,
httpStatus: 200,
httpBody: { n: 20, result: 6765 },
};
cases.push({
name: 'process_pool_reuse_and_http_offload',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await new Promise((resolve) => server.close(resolve));
await pool.close();
}
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`exec` 启动 Shell 并缓冲完整输出,适合短命令但须防范命令注入;`execFile` 跳过 Shell 直接执行二进制文件,更安全;`spawn` 以流方式持续输出无缓冲上限,适合大数据或长任务;`fork` 专用于运行 Node.js 模块并内置父子进程 IPC 消息通道,适合构建常驻进程池。