ps:仅获取父进程的干净方法?
我使用ps ef并ps rf不少。
这是以下示例输出ps rf:
  PID TTY      STAT   TIME COMMAND 3476 pts/0    S      0:00 su ...
 3477 pts/0    S      0:02  \_ bash
 8062 pts/0    T      1:16      \_ emacs -nw ...
15733 pts/0    R+     0:00      \_ ps xf
15237 ?        S      0:00 uwsgi ...
15293 ?        S      0:00  \_ uwsgi ...
15294 ?        S      0:00  \_ uwsgi ...
今天,我只需要在脚本中检索uwsgi 的 (因此我只需要15237,而不想要15293或15294)。
从今天开始,我尝试了一些ps rf | grep -v ' \\_ '……但是我想要一种  。
我还遇到了unix.com论坛中的另一种解决方案:
ps xf | sed '1d' | while read pid tty stat time command ; do [ -n "$(echo $command | egrep '^uwsgi')" ] && echo $pid ; done但是仍然有 和 。
真的没有ps选择或更巧妙的技巧(也许使用  )来完成该任务吗?
回答:
与@netcoder讨论答案后,他使用了一个不错的技巧:D
使用fon ps总是可以使父项位于最前面。
这应该工作:
$ ps hf -opid -C <process> | awk '{ print $1; exit }'正如我在评论中提到的那样,这只会返回pid一个过程。
我会去:
ps rf -opid,cmd -C <process-name> | awk '$2 !~ /^[|\\]/ { print $1 }'那是:
- 列出正在运行的进程r(或者e如果您需要所有内容)
- 连同父母/孩子图 f
- 仅输出pid和命令名称 -opid,cmd
- 仅针对给定的过程 -C <process>
然后
- 如果第二个字段(即命令(-opid,cmd))不是以a开头,\或者|它是父进程,那么请打印第一个字段(即pid)。
简单测试:
$ ps f -opid,cmd -Cchromium  PID CMD
 2800 /usr/lib/chromium/chromium --type=zygote --enable-seccomp-sandbox
 2803  \_ /usr/lib/chromium/chromium --type=zygote --enable-seccomp-sandbox
 2899      \_ /usr/lib/chromium/chromium --type=renderer --enable-seccomp-sandbox --lang=en-US --force-fieldtrials=ConnCountImpact/conn_count_6/ConnnectB
 2906      |   \_ /usr/lib/chromium/chromium --type=renderer --enable-seccomp-sandbox --lang=en-US --force-fieldtrials=ConnCountImpact/conn_count_6/Connn
 [  ... snip ... ]
 2861      \_ /usr/lib/chromium/chromium --type=renderer --enable-seccomp-sandbox --lang=en-US --force-fieldtrials=ConnCountImpact/conn_count_6/ConnnectB
 2863          \_ /usr/lib/chromium/chromium --type=renderer --enable-seccomp-sandbox --lang=en-US --force-fieldtrials=ConnCountImpact/conn_count_6/Connn
 2794 /usr/lib/chromium/chromium --enable-seccomp-sandbox --memory-model=low --purge-memory-button --disk-cache-dir=/tmp/chromium
 2796  \_ /usr/lib/chromium/chromium --enable-seccomp-sandbox --memory-model=low --purge-memory-button --disk-cache-dir=/tmp/chromium
 3918  \_ /usr/lib/chromium/chromium --type=gpu-process --channel=2794.45.1891443837 --gpu-vendor-id=0x10de --gpu-device-id=0x0611 --gpu-driver-version -
25308  \_ [chromium] <defunct>
31932  \_ /usr/lib/chromium/chromium --type=plugin --plugin-path=/usr/lib/mozilla/plugins/libflashplayer.so --lang=en-US --channel=2794.1330.1990362572
$ ps f -opid,cmd -Cchromium | awk '$2 !~ /^[|\\]/ { print $1 }'
PID
2800
2794
$ # also supressing the header of ps (top line 'PID') -- add 'h' to ps
$ ps hf -opid,cmd -Cchromium | awk '$2 !~ /^[|\\]/ { print $1 }'
2800
2794
以上是 ps:仅获取父进程的干净方法? 的全部内容, 来源链接: utcz.com/qa/416616.html







