简体   繁体   English

无法理解ps | wc输出差异

[英]Can't understand ps | wc output differences

I was trying to write a set of functions that could check to see if a process name was running when I encountered some unexpected output. 我试图编写一组函数,这些函数可以在遇到意外输出时检查进程名称是否正在运行。 I've condensed the issue in the following script names isRunning.sh which depends on a system ps command that can take the '-fC' arguments... 我在以下脚本名称isRunning.sh中浓缩了该问题,该脚本名称取决于可以使用'-fC'参数的系统ps命令...

#!/bin/bash
progname=isRunning.sh
ps -fC isRunning.sh
pRet=`ps -fC ${progname} | wc -l`
echo pRet $pRet
psOut=`ps -fC ${progname}` 
wcOut=`echo "${psOut}" | wc -l`
echo
echo ps output
echo "${psOut}"
echo
echo wcOut $wcOut

The first attempt at piping the ps output to wc gets a return of 3. The second attempt gets the expected return value of 2. Can anyone explain this behavior? 第一次尝试将ps输出传递给wc的返回值为3。第二次尝试的预期返回值为2。有人可以解释此现象吗? I figure it's got to be something stupid I am overlooking. 我认为这一定是我忽略的愚蠢之举。

Thanks, bbb 谢谢,bbb

edit: my output 编辑:我的输出

UID        PID  PPID  C STIME TTY          TIME CMD
root      6717  5940  0 13:10 pts/0    00:00:00 /bin/bash ./isRunning.sh
pRet 3

ps output
UID        PID  PPID  C STIME TTY          TIME CMD
root      6717  5940  0 13:10 pts/0    00:00:00 /bin/bash ./isRunning.sh

wcOut 2

I get 2 both attempts. 我都尝试两次。 Your ps might be outputting an extra blank line, or somesuch, and then your shell's backtick expansion stripping it. 您的ps可能正在输出一个额外的空白行或类似的行,然后您的shell的反引号扩展剥离了它。 Or maybe you actually had two processes matching the first time you ran it. 或者,也许您实际上有两个匹配的过程在您第一次运行时就匹配了。

If you just want to see if its running, check the exit code from your ps: 如果只想查看其运行状态,请检查ps的退出代码:

if ps -C "${progname}" > /dev/null; then
  echo its running
else
  echo not running
fi

Even better, you should take a look at pidof and pgrep if you can rely on them being present on whichever systems you're targeting. 更好的是,如果可以依靠pidofpgrep则可以依靠它们出现在目标系统中。 Or use the LSB functions, if you're on Linux. 或使用LSB功能(如果您使用的是Linux)。

edit: Actually, since you're looking for copies of yourself running, you might be picking up the shell doing a fork to implement the pipe. 编辑:实际上,由于您正在寻找自己正在运行的副本,因此您可能会捡起外壳来进行分叉以实现管道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM