killing child process in Node.js

53 Views Asked by At

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);
    }
})();
1

There are 1 best solutions below

1
arpan.r On BEST ANSWER

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);
    }
})();