Bird
0
0

You want to create a Node.js cluster that forks a worker for each CPU core and logs each worker's process ID. Which code snippet correctly achieves this?

hard📝 Application Q8 of 15
Node.js - Cluster Module
You want to create a Node.js cluster that forks a worker for each CPU core and logs each worker's process ID. Which code snippet correctly achieves this?
Aconst cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpus = os.cpus().length; for (let i = 0; i < cpus; i++) { const worker = cluster.fork(); console.log(`Worker ${worker.process.pid} started`); } }
Bconst cluster = require('cluster'); if (cluster.isWorker) { console.log(`Worker ${process.pid} started`); } else { cluster.fork(); }
Cconst cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { cluster.fork(os.cpus().length); }
Dconst cluster = require('cluster'); if (cluster.isMaster) { for (let i = 0; i < 4; i++) { cluster.fork(); } console.log('Workers started'); }
Step-by-Step Solution
Solution:
  1. Step 1: Use os.cpus().length to get CPU count

    This is needed to fork one worker per CPU core.
  2. Step 2: Fork workers in a loop and log each worker's PID

    const cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpus = os.cpus().length; for (let i = 0; i < cpus; i++) { const worker = cluster.fork(); console.log(`Worker ${worker.process.pid} started`); } } correctly forks and logs each worker's process ID.
  3. Step 3: Check other options for correctness

    const cluster = require('cluster'); if (cluster.isWorker) { console.log(`Worker ${process.pid} started`); } else { cluster.fork(); } forks only one worker, C incorrectly calls fork with argument, D forks 4 workers but does not log PIDs.
  4. Final Answer:

    Option A correctly forks per CPU and logs worker PIDs -> Option A
  5. Quick Check:

    Fork per CPU and log PID = const cluster = require('cluster'); const os = require('os'); if (cluster.isMaster) { const cpus = os.cpus().length; for (let i = 0; i < cpus; i++) { const worker = cluster.fork(); console.log(`Worker ${worker.process.pid} started`); } } [OK]
Quick Trick: Use os.cpus().length and loop to fork workers [OK]
Common Mistakes:
  • Calling cluster.fork with arguments
  • Not logging worker PIDs
  • Forking fixed number without CPU count

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes