开发者

Node.js grep process (but don't include self)

So, from the docs, I can grep if a process exists or not. But if it doesn't, I get a returned result of self. I can do this by executing the actual statement, but what about node.js way?! I've tried multiple greps, but maybe somebody has already done this... I just need to add an extra | grep -v |, essentially.

var util   = require('util'),
    spawn = require('child_process').spawn,
    ps    = spawn('ps', ['ax']),
    grep  = spawn('grep', ['MyProcessThatIsNotRunning']);


ps.stdout.on('data', function (data) {
  grep.stdin.write(data);
});

ps.stderr.on('data', function (data) {
  console.log('ps stderr: ' + data);
});

ps.on('exit', function (code) {
  if (code !== 0) {
    console.log('ps process exited with code ' + code);
  }
  grep.stdin.end();
});

grep.stdout.on('data', function (data) {
  console.log(data.toString());
});

grep.stderr.on('data', function (data) {
  console.log('grep stderr: ' + data);
});

grep.on('exit', function (code) {
  if (code !== 0) {
    console.log('grep process exited with code ' +开发者_JAVA技巧 code);
  }
});


Why not using child_prosses.exec ?

var cmdline = 'ps ax | grep -v grep | grep MyProcessThatIsNotRunning';
require('child_process').exec(cmdline, function (error, stdout, stderr) {
    if (error)
    {
        console.error(error); process.exit(1);
    }
    // parse 'ps ax | grep -v grep | grep MyProcessThatIsNotRunning' result here
    console.log(stdout);
});


For the above answer you can try

var cmdline = 'ps ax | grep MyProcessThatIsNotRunnin[g]';

or

grep  = spawn('grep', ['MyProcessThatIsNotRunnin[g]']); 
//should work didn't test though.. :)

The square brackets is a trick to not find the grep.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜