Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS- get process ID from within shell script exec

I have some NodeJS code which runs a shell script using child_process.exec(). Within this shell script I run a program someProgram. What I would like to do is get the PID of someProgram and pass that back into my Javascript code so I can later kill that specific process with another child_process.exec() call. Is this possible?

like image 923
user2871915 Avatar asked Oct 30 '25 15:10

user2871915


1 Answers

var exec = require('child_process').exec;
var pid = {};
exec('. ./script.sh', function(err, stdout, stderr) {
  console.log(stdout);
  setTimeout(function() {
    exec('kill ' + pid, function(err, stdout, stderr) {
      console.log(stdout);
    });
  }, 6000);

});

exec('pgrep -f someProgram', function(err, stdout, stderr) {
  console.log('stdout' + stdout);
  pid = stdout;
  console.log('pid ' + pid);
});

just note that the bottom exec would run concurrently. You could use this in a gulpfile, etc.

like image 145
Evan Avatar answered Nov 01 '25 04:11

Evan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!