NodeJs的"Child Process"是如何与事件循环交互的?

How does NodeJs's "Child Process" interact with the event loop?

我担心的是它是否阻塞了事件循环。因此,如果我确实调用了一个内部脚本,它会在脚本的生命周期内阻止事件循环,还是会在自己的线程上激活?

  const { spawn } = require('child_process');
  const pythonscript = spawn('py script.py');//assume this just runs forever

我从文档中清楚地读到这样做会产生一个新进程,但是这个新进程是否与 Nodejs 应用程序共享同一个线程,还是它有自己的线程?例如如果我检查 运行 个进程,我真的会看到 "script.py" 个进程吗?

如果这是一个 OS 特定问题,请根据该假设提供答案。

除非使用 *Sync 函数(如 execFileSync),否则不会阻塞事件循环。

有关详细信息,请参阅 the child_process docs

My concern was surrounding if it blocked the event loop.

没有。使用任何不以 Sync 结尾的 child_process 方法启动新的子进程不会阻止您的事件循环。有一小段执行时间来命令 OS 启动新进程,然后它 returns 然后你回到你自己的事件循环,独立于子进程正在做什么。

So if I did call an internal script would it block the event loop for the life of the script or does it activate on its own thread?

一个"child process"是一个新的"process"。那不是您流程中的线程。这是一个全新的过程。

I read quite clearly from the documentation that doing this spawns a new process, but does that new process share the same thread as the Nodejs app or does it get a thread of its own?

每个进程都有自己的主线程。所以,你启动的新子进程在它自己的进程中有它自己的独立线程,完全独立于父进程。

Would I literally see a "script.py" process if I checked my running processes?

是的,你会的。这将是一个 python 过程 运行 script.py.

If this is an OS specific question, please provide an answer with that assumption.

所有操作系统的答案都是一样的。


现在,如果您使用了 Sync 方法之一,例如 child_process.spawnSync(),那么它仍然会在自己的进程中启动子进程(它有自己的主线程),但是通过选择Sync 版本的方法,您已明确要求 node.js 进程阻止事件循环,直到子进程完成(本质上是在它执行任何其他操作之前等待它)。此行为仅适用于 spawnSync()execFileSync()execSync().