ps: Clean way to only get parent processes?

后端 未结 9 774
忘了有多久
忘了有多久 2020-12-15 00:28

I use ps ef and ps rf a lot.

Here is a sample output for ps rf:

  PID TTY      STAT   TIME COMMAND
 3476 pts/0         


        
9条回答
  •  佛祖请我去吃肉
    2020-12-15 01:02

    After discussing with @netcoder on his answer's comments he used a nice trick :D
    Using f on ps will always get the parent on top which is great.

    This should just work:

    $ ps hf -opid -C  | awk '{ print $1; exit }'
    

    as I mention on the comments, this will return the pid of just one process.


    I would go with:

    ps rf -opid,cmd -C  | awk '$2 !~ /^[|\\]/ { print $1 }'
    

    that is:

    • list running processses r (or e if you want everything)
    • along with parent/children graph f
    • output only the pid and command name -opid,cmd
    • only for the given process -C

    and then

    • if the 2nd field - which is the command (-opid,cmd) - does not start with a \ or | then it is a parent process, so print the 1st field - which is the pid.

    simple test:

    $ 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] 
    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
    

提交回复
热议问题