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?
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?
- Does your shell script opens the program as a separate process? If it doesn't, can't you use child_process.pid ? – Michele Ricciardi Commented Jul 22, 2015 at 18:34
- My shell script runs the program as a background process. Won't child_process.pid just get me the pid of the shell script and not the program within it? – user2871915 Commented Jul 22, 2015 at 18:39
- Yes you are correct, that's what I was trying to ask. I know that in C you can use 'pipe' to pass data between processes, perhaps once the shell scripts spawns the separate process, you could pass the pid using a pipe to the JS? I haven't done this with node so not sure whether possible or most elegant way of doing so. – Michele Ricciardi Commented Jul 22, 2015 at 18:48
1 Answer
Reset to default 3var 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.