Abe
Abe

Reputation: 441

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

My concern was surrounding if it blocked the event loop. 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?

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

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? e.g. Would I literally see a "script.py" process if I checked my running processes?

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

Upvotes: 3

Views: 1927

Answers (2)

jfriend00
jfriend00

Reputation: 707328

My concern was surrounding if it blocked the event loop.

No. Launching a new child process with any of the child_process methods that do NOT end in Sync does not block your event loop. There's a momentary amount of execution time to command the OS to launch the new process and then it returns and you are back to your own event loop, independent of whatever the child process is doing.

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?

A "child process" is a new "process". That's not a thread in your process. It's a whole new 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?

Each process has it's OWN main thread. So, the new child process you start has it's own separate thread in it's own process, completely independent from the parent.

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

Yes, you would. It would be a python process running script.py.

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

The answer is the same for all operating systems.


Now, if you used one of the Sync methods such as child_process.spawnSync(), then it still starts the child in its own process (which has it's own main thread), but by choosing the Sync version of the method, you've explicitly asked your node.js process to block the event loop until the child process finishes (essentially to wait for it before it does anything else). This behavior is only for spawnSync(), execFileSync() and execSync().

Upvotes: 4

mrm
mrm

Reputation: 5222

You won't block the event loop unless you use the *Sync functions (like execFileSync).

See the child_process docs for details.

Upvotes: 2

Related Questions