Search code examples
node.jscluster-computingkill

killing child process in Node.js


If the child process is caught in an infinite loop, the 'exit' event is never handled. How do you force a worker to stop in this case?

"use strict";

(async () => {
    const cluster = require("cluster");

    if (cluster.isMaster) {
        const worker = cluster.fork()
            .on("exit", () => {
                console.log("ici!!!");
            })
        ;
        
        await new Promise(resolve => setTimeout(resolve, 2_000));
        
        worker.kill("SIGINT");
    }
    else {
        while (true);
    }
})();

Solution

  • Here is the example code to kill using the worker.process.kill() method with the "SIGTERM" signal

    "use strict";
    
    (async () => {
        const cluster = require("cluster");
    
        if (cluster.isMaster) {
            const worker = cluster.fork();
    
            worker.on("exit", (code, signal) => {
                if (code !== 0) {
                    console.log(`Worker process exited with code ${code}, signal ${signal}`);
                    // You can choose to respawn the worker here if needed.
                }
            });
    
            await new Promise(resolve => setTimeout(resolve, 2000));
    
            // Send a SIGTERM signal to forcefully terminate the worker process.
            worker.process.kill("SIGTERM");
        } else {
            while (true);
        }
    })();