检查进程是否正在运行
我正在尝试检查进程是否正在运行。如果它正在运行,我想要返回值“OK”,如果没有运行,则返回值“Not OK”。如果这是正确的术语,我只能使用“ps”而不附加任何其他参数(例如 ps -ef)。我的代码是:
if ps | grep file; then echo 'OK'; else echo 'NO'; fi
问题是它不搜索确切的过程并且总是返回“确定”,我不想显示所有信息我只想知道文件是否存在。
I am trying to check if a process is running. If it is running I want a return value of 'OK' and if not a return value of 'Not OK'. I can only use 'ps' without any other arguments attached (eg. ps -ef) if thats the correct term. The code I have is:
if ps | grep file; then echo 'OK'; else echo 'NO'; fi
The problem with this is that it does not search for the exact process and always returns 'OK', I don't want all the information to appear I just want to know if the file exists or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
将
grep
替换为真正的问题:避免完全使用
grep
的问题。Spare
grep
for real problems:avoids the problem of using
grep
altogether.那么“pgrep”呢?
其中 xxxx 是以名称 foo 运行的二进制文件的 pid。如果 foo 没有运行,则没有输出。
还:
如果 foo 正在运行,将打印“yes”;如果没有,就说“不”。
请参阅 pgrep 手册页。
What about "pgrep"?
where xxxx is the pid of the binary running with the name foo. If foo is not running, then no output.
Also:
will print "yes" if foo is running; "no" if not.
see pgrep man page.
当我知道 pid 时,我更喜欢:
When I know the pid I prefer:
grep -v grep 确保您得到的结果不是正在执行的 grep 语句。
grep -v grep makes sure that the result you get is not the grep statement in execution.
grep 也有一个解决方案:
这在 Debian 6 中工作正常,不确定其他发行版。需要
'{print $11}'
,因为系统也将 grep 视为一个进程。There is a solution with grep as well:
This works fine in Debian 6, not sure about other distros.
'{print $11}'
is needed, because the sytem treats grep as a process as well.您的代码始终返回“OK”,因为 grep 发现自己位于进程列表中(“grep file”包含单词“file”)。解决方法是执行“grep -e [f]ile”(-e 表示正则表达式),但它找不到自己。
Your code always returns 'OK', because grep finds itself in the process list ('grep file' contains the word 'file'). A fix would be to do a `grep -e [f]ile' (-e for regular expression), which doesn't find itself.