Node.js命令在使用pgrep时出错
在我的代码中,我需要检查程序是否启动。 要做到这一点,我有一个“运行”function:
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 } }); }
它有一段时间运作良好,但现在我得到:
Error: { [Error: Command failed: ] [stack]: [Getter/Setter], [arguments]:undefined, [type]: undefined, [message]: 'Command failed: ', killed: false, code: 1, signal: null }
(stderr是空的)
我不明白为什么,所以不能想到任何解决scheme。
有没有人可以告诉我为什么我得到这个错误?
如果没有与您的请求匹配的进程, pgrep
将返回非零状态。 Node将把这个非零状态解释为pgrep
失败的意思。 这可以很容易地在shell中检查,通过使用echo $?
向您显示前一个命令的退出状态。 假设你有一些bash
实例在运行
$ pgrep --count bash; echo $?
您将在控制台上看到正在运行的bash
实例的数量以及将为0
的退出代码。 现在,如果你尝试一些不存在的东西:
$ pgrep --count nonexistent; echo $?
你会看到一个数为0
,退出状态为1
。
以下是关于退出状态的pgrep
手册页:
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.
所以你可以用这样的东西检查结果:
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);
var arg = 'pgrep --count ' + app,
这里有两个问题:
-
在Linux上,它不是 –
--count
它是-c
-
该行应以a结尾
;
,而不是逗号。