Linux Command - 'ps'

3
我的目标是找到具有最高PID的进程(是的,我知道可以使用ps -ef | tail -n 1,但我想先找到PID,然后再找到进程),所以我使用以下命令查找具有最高PID的进程: ps -ef | cut -d " " -f 6 | sort | tail -n 1 然后我发现ps -p可以获取最高PID并输出匹配的进程(当我手动复制PID时可以工作),但由于某种原因,当我在它们之间加上'|'时,它会显示语法错误。请问有人能指出问题在哪里吗? 此外,如果您有更好的方法,请告诉我。 谢谢, Dean
PS:完整的不起作用的命令是: ps -ef | cut -d " " -f 6 | sort | tail -n 1 | ps -p
2个回答

4

提供程序参数和写入程序标准输入之间存在差异,您正在执行后者。在第一种情况下,程序将参数列表读取为字符串数组,可以由程序解释。在第二种情况下,程序实际上从一个特殊文件中读取并处理其内容。您在程序名称后面添加的所有内容都是参数。ps期望许多可能的参数,例如-p和进程的PID。在您的命令中,您没有将PID作为参数提供,而是写入ps的stdin中,但该程序会忽略它。

但是,您可以使用xargs,它读取其标准输入并将其用作命令的参数:

ps -ef | cut -d " " -f 6 | sort | tail -n1 | xargs ps -p

这是xargs的功能(来自man):

xargs - build and execute command lines from standard input

或者您可以使用命令替换,就像janos所展示的那样。在这种情况下,shell会将$()内部的表达式作为一个命令来评估,并代替其输出。因此,在扩展发生后,您的命令看起来像是ps -p 12345

man bash

Command Substitution
   Command substitution allows the output of a command to replace the com‐
   mand name.  There are two forms:

          $(command)
   or
          `command`

   Bash performs the expansion by executing command and replacing the com‐
   mand substitution with the standard output of  the  command,  with  any
   trailing newlines deleted.  Embedded newlines are not deleted, but they
   may be removed during word splitting.  The command  substitution  $(cat
   file) can be replaced by the equivalent but faster $(< file).

你能详细介绍一下这两个系统和命令替换吗? - user2559696
@user2559696,这是你需要的,我尽量添加了更多细节。 - Lev Levitsky
另外,如果您的ps命令支持“-o”选项,则可以指定要打印的列。例如,“ps -eo pid”将打印PID,“ps -eo pid,ppid”将同时打印PID和PPID。使用此选项,您无需剪切ps的输出。还有一点需要注意的是,您的脚本将从高PID和运行的进程开始。您的输出可能会捕获那些PID而不是您想要捕获的实际进程。 - alvits

3
也许您正在寻找这个:
ps -p $(ps -ef | cut -d " " -f 6 | sort | tail -n 1)

也就是说,ps -p PID命令会打印出命令行中指定PID的详细信息。它不能从标准输入中获取参数。

或者你可以使用xargs,如Lev Levitsky所示;-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接