Node.js

[Node.js] child_process

2018-10-19  本文已影响96人  何幻

child_process是node中的一个内置模块,
它提供了衍生(spawn)子进程的功能。

1. fork示例

index.js

const childProcess = require('child_process');

console.log('1. start fork');
const child = childProcess.fork('./child.js');

console.log('2. start on message');
child.on('message', function () {
    console.log('9. end message');
});

console.log('3. start send');
child.send({ a: 1 });
console.log('4. end send');

child.js

console.log('5. in child - start message');
process.on('message', function () {
    console.log('6. in child - end message');

    console.log('7. in child - start send');
    process.send({ a: 2 });
    console.log('8. in child - end send');
});

则日志信息如下,

$ node index.js
1. start fork
2. start on message
3. start send
4. end send
5. in child - start message
6. in child - end message
7. in child - start send
8. in child - end send
9. end message
(挂住)

fork会建立一个永久的channel,以供进程间通信。
因此,以上日志打印完后,会挂住。

可以使用child.disconnect()关闭这个通道。

child.on('message', function () {
    console.log('9. end message');

    // 关闭channel
    child.disconnect();
});

2. spawn

child_process.spawn() 方法使用给定的 commandargs 中的命令行参数来衍生一个新进程。
如果省略 args,则默认为一个空数组。

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`子进程退出码:${code}`);
});

它会执行命令行操作,

$ ls -lh /usr

3. 其他

  1. child_process.exec(): 衍生一个 shell 并在 shell 上运行命令,当完成时会传入 stdout 和 stderr 到回调函数。
  2. child_process.execFile(): 类似 child_process.exec(),但直接衍生命令,且无需先衍生 shell。
  3. child_process.fork(): 衍生一个新的 Node.js 进程,并通过建立 IPC 通讯通道来调用指定的模块,该通道允许父进程与子进程之间相互发送信息。
  4. child_process.execSync(): child_process.exec() 的同步函数,会阻塞 Node.js 事件循环。
  5. child_process.execFileSync(): child_process.execFile() 的同步函数,会阻塞 Node.js 事件循环。

参考

node v8.12.0 docs: child_process
node v10.12.0 中文文档:子进程

上一篇 下一篇

猜你喜欢

热点阅读