为什么结果等于 0,有时等于 1 - shell_exec('pgrep -f

Why is the result equal to 0 and sometimes 1 - shell_exec('pgrep -f

脚本:

$S = 'pgrep -f test.php | wc -l';
$U = trim(shell_exec($S));
echo $U;

为什么这个脚本的结果等于 0 有时 1

文件 test.php 不是 运行。

问题是在执行命令 pgrep -f test.php | wc -l 时,它有时会在结果中显示自己(取决于时间)。您可以根据 a question on Linux & Unix SE 使用以下语法防止这种情况发生:

pgrep -f '[t]est.php' | wc -l

中括号的部分基本上是说"find the letter t followed by est.php",如果是运行会找到文件,但不会匹配当前执行的命令,因为t之后括号 [.