我担心的是它是否阻塞了事件循环。因此,如果我确实调用了内部脚本,它会在脚本的生命周期内阻塞事件循环还是会在自己的线程上激活?
const { spawn } = require('child_process');
const pythonscript = spawn('py script.py');//assume this just runs forever
我从文档中清楚地读到,执行此操作会生成一个新进程,但是该新进程是否与 Nodejs 应用程序共享相同的线程,或者它是否获得自己的线程?例如如果我检查正在运行的进程,我真的会看到“script.py”进程吗?
如果这是操作系统特定的问题,请根据该假设提供答案。
最佳答案
My concern was surrounding if it blocked the event loop.
没有。使用任何不以 Sync 结尾的 child_process 方法启动新的子进程不会阻止事件循环。有一段短暂的执行时间来命令操作系统启动新进程,然后它返回,您将回到自己的事件循环,与子进程正在执行的任何操作无关。
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?
“子进程”是一个新的“进程”。那不是您进程中的线程。这是一个全新的过程。
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?
是的,你会的。这将是一个运行 script.py
的 python 进程。
If this is an OS specific question, please provide an answer with that assumption.
对于所有操作系统,答案都是相同的。
<小时/>现在,如果您使用了 Sync
方法之一,例如 child_process.spawnSync()
,那么它仍然会在自己的进程中启动子进程(该进程有自己的进程)主线程),但是通过选择该方法的 Sync 版本,您已明确要求您的 node.js 进程阻止事件循环,直到子进程完成(本质上是在子进程完成之前等待它)还要别的吗)。此行为仅适用于 spawnSync()
、execFileSync()
和 execSync()
。
关于javascript - NodeJs的 "Child Process"如何与事件循环交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60498538/