创建子进程
NodeJs使用child_process
模块来创建子进程。基础的两个方法为child_process.spawn()
、child_process.spawnSync()
,前者异步地创建子进程,且不阻塞 Node.js 事件循环;后者则以同步的方式提供等效功能,但会阻止事件循环直到衍生的进程退出或终止。由于child_process.spawnSync()
不常用,此处不做介绍。child_process
模块基于child_process.spawn()
方法实现了其他几个创建子进程方法,简要介绍如下:
child_process.spawn(command[, args][, options])
:根据命令创建子进程,返回子进程对象,可以在子进程对象上注册事件child_process.exec(command[, options][, callback])
:创建一个shell环境进程并在该shell中运行命令,UNIX上是 ‘/bin/sh’,windows上是’cmd.exe’,可通过options.shell
指定程序child_process.execFile(file[, args][, options][, callback])
:类似于child_process.exec()
,不创建shell直接根据命令创建子进程child_process.fork()
:创建一个新的 Node.js 进程,并通过建立 IPC 通信通道来调用指定的模块,该通道允许在父进程与子进程之间发送消息。进程间通信
IPC的全称是Inter-Process Communication,即进程间通信。Node中实现IPC通道的是管道(pipe)技术,具体细节实现依赖系统底层。借用《深入浅出Node.js》中的图来表示创建IPC管道的过程,如下:
IPC 通信方式有:Pipe fifo,massage queue, signal,shared memory(共享内存),semaphone(信号量),file(文件),sokect(套接字)等。Nodejs 使用管道的方式实现。
NodeJs提供了子进程和集群模块,帮助我们使用NodeJs多进程来充分利用CPU资源和提高应用的健壮性。
Nodejs进程间通过监听message
事件接收消息,使用send()
方法发送消息,它们是基于IPC实现的。
// parent.js
const { fork } = require('child_process')
const path = require('path')
const child = fork(path.resolve(__dirname, './child.js'))
child.on('message', function (msg) {
console.log('Message from child: ', msg)
})
child.send('hello world')
// child.js
process.on('message', function (msg) {
console.log('Message from parent:', msg)
process.send(msg)
})