最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS- get process ID from within shell script exec - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Jul 22, 2015 at 17:38 user2871915user2871915 4698 silver badges17 bronze badges 3
  • 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
Add a ment  | 

1 Answer 1

Reset to default 3
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.

发布评论

评论列表(0)

  1. 暂无评论