06 / 09

Describe fork, spawn and exec.

There are three primary ways to create a child process in Node.js:
  1. 1

    child_process.exec(): exec spawns a shell and runs a command, then buffers the entire output before passing it to a callback function.

  2. 2

    child_process.spawn(): spawn launches a new process and returns a ChildProcess object that provides a streaming interface for communication.

  3. 3

    child_process.fork(): This method is a special case of spawn() method to create child processes. It creates a new instance of the V8 engine and the Node.js runtime to execute a specific JavaScript module.

Difficulty: 5/10
Topics: process creation, child_process API, resource management

Scenario Questions

0-2 years experience
  1. 1

    You need to run a simple shell command from a Node.js script to list files. Which child_process method would you choose and why?

  2. 2

    If you call child_process.fork to start a worker script and then immediately call process.exit in the parent, what happens to the child?

2-5 years experience
  1. 1

    Our service spawns a child process to run a Python script for image processing. Occasionally the child hangs and never returns. Walk me through how you'd debug this using spawn vs exec.

  2. 2

    We switched from child_process.spawn to child_process.exec for a data‑import job and saw memory usage spike. Explain why that happened and what trade‑offs you’d consider.

5-8 years experience
  1. 1

    Design a Node.js microservice that needs to process thousands of concurrent video transcoding tasks using child processes. How would you decide between fork, spawn, and a worker‑thread pool, and what limits would you enforce?

  2. 2

    Explain how you’d handle graceful shutdown of a Node.js server that has multiple long‑running child processes started via fork, ensuring no orphan processes remain.

8+ years experience
  1. 1

    Our platform currently uses child_process.fork for each user request, leading to resource exhaustion at scale. Propose a migration strategy to a more scalable architecture, considering monitoring, deployment, and backward compatibility.

  2. 2

    Discuss the security implications of using exec to run user‑provided commands in a SaaS product, and outline policies or sandboxing techniques you’d put in place.

Follow-up Questions

  • What are the main differences in stdio handling between spawn and exec?
  • How does fork provide IPC compared to spawn?
  • When would you prefer spawn over fork for a CPU‑bound task?