Search code examples
node.jsprocesschild-processpm2restart

Restart an external process from within a nodejs app (linux)


Say that I am running a process from the command line (NOT a nodejs app):

myProcess doSomething --withParam1

I am also running a nodejs app that connects to this process (rpc).

node myApp

myProcess will randomly silently fail to work properly without crashing and myApp will detect it. I need myApp to be able to restart myProcess (kill it and start it again). After I restarted myProcess, myApp will also restart itself using pm2 (I am already handling the pm2 restart part for the nodejs app - my issue is that I cannot use pm2 to restart myProcess since it is not a nodejs app). Also, I cannot change the code of myProcess since it is a 3rd party software.

How can I restart the external process from my nodejs app?


Solution

  • I ended up using process.kill to kill the process and nodejs child process to restart it.

    To find the pid of the process before killing it, I used this:

    const childProcess = require('child_process');
    
    function printPid() {
        childProcess.exec('pidof -s myProcess', function(error, stdout, stderr) {
            if (error) {
                console.log(error);
            } else {
                console.log(stdout);
            }
        });
    }