DrakaSAN
DrakaSAN

Reputation: 7853

Node.js command get error while using pgrep

In my code, I need to check if a program is started. To do so, I have a function 'running':

function running(app, callback) {
    var arg = 'pgrep --count ' + app;
    exec( arg, function(err, stdout, stderr) {
        if (err) {
            console.log('Error:' + inspect(err) + ' ' + stderr);
            callback('0');
        } else {
            var data = '' + stdout;
            callback(data.charAt(0)); //Will be 0 only if no app is started
        }
    });
}

It worked well for some times, but now I get:

Error: { [Error: Command failed: ]
[stack]: [Getter/Setter],
[arguments]:undefined,
[type]: undefined,
[message]: 'Command failed: ',
killed: false,
code: 1,
signal: null }  

(stderr is empty)

I don t understand why and so can t think of any solution.

Does anyone could tell me why do I get this error?

Upvotes: 2

Views: 1277

Answers (2)

Louis
Louis

Reputation: 151380

pgrep will return a non-zero status if there are no processes matching your request. Node will interpret this non-zero status as meaning that pgrep failed. This can easily be checked at the shell, by using echo $? which shows you the exit status of the previous command. Assuming you have some bash instances running

$ pgrep --count bash; echo $?

You'll see on the console the number of bash instance running and the exit code which will be 0. Now, if you try with something that does not exist:

$ pgrep --count nonexistent; echo $?

You'll see a count of 0 and an exit status of 1.

Here is what the man page for pgrep says about the exit status:

EXIT STATUS
    0      One or more processes matched the criteria.
    1      No processes matched.
    2      Syntax error in the command line.
    3      Fatal error: out of memory etc.

So you could check the result with something like this:

var count;
if (err) {
    if (err.code === 1)
        count = 0; // Status 1 means no match, so we don't have to parse anything.
    else {
        // Real error, fail hard...
    }
}
else {
    count = ... ; // parse count from stdout
}
callback(count);

Upvotes: 3

Joe
Joe

Reputation: 42607

var arg = 'pgrep --count ' + app,

There are two issues here:

  1. on Linux, it's not --count it's -c

  2. that line should end with a ;, not a comma.

Upvotes: 0

Related Questions