모든 상위 프로세스를 보는 방법은 무엇입니까?

모든 상위 프로세스를 보는 방법은 무엇입니까?

특정 프로세스 이름의 모든 인스턴스의 모든 상위 항목을 보는 방법은 무엇입니까?

답변1

pstree프로그램은 이에 매우 적합한 것 같습니다.

$ pidof bash | xargs -n 1 pstree -sp
init(1)───lightdm(1284)───lightdm(1577)───init(2017)───gnome-terminal(2595)───bash(18001)───man(10946)───pager(10955)
init(1)───lightdm(1284)───lightdm(1577)───init(2017)───gnome-terminal(2595)───bash(12895)
init(1)───sshd(1181)───sshd(11860)───sshd(11938)───bash(11939)───xargs(12124)───pstree(12127)
init(1)───sshd(1181)───sshd(9235)───sshd(9316)───bash(9317)
init(1)───lightdm(1284)───lightdm(1577)───init(2017)───gnome-terminal(2595)───bash(2897)

답변2

이를 달성하기 위해 다음 줄을 공식화했습니다. 더 나은 방법이 있을 수 있습니다. 정규식은 /[b]ash/일치시킬 프로세스 이름을 선택하는 데 사용됩니다.

ps -ef | awk ' NR == 1 { header = $0; next } { pid[$2] = $0 } /[b]ash/ { toprint[$2] } END { print header; for (i in toprint) { while (i != 1) { split(pid[i], pieces, " "); i = pieces[3]; toprint[i] } } for (i in toprint) { print pid[i] } }'

실제로 처음에는 전체 스크립트로 작성한 다음 더 읽기 쉬운 버전은 다음과 같습니다.

ps -ef | awk '
NR == 1 {
  header = $0
  next
}
{
  pid[$2] = $0                    # Save all lines of ps -ef in this array, stored by PID
}
/[b]ash/ {                        # Modify this regex to change the filter
  toprint[$2]                     # Designate all these PIDs as "to print"
}
END {
  print header
  for (i in toprint) {            # For each PID designated "to be printed":
    while (i != 1) {
      split(pid[i], pieces, " ")  # Look up the info on that process
      i = pieces[3]               # Set i to the PPID
      toprint[i]                  # Designate that PPID as "to print"
    }                             # Recurse to get the parent of that process, until PID 1 is reached.
  }
  for (i in toprint) {            # Then actually print the data.
    print pid[i]
  }
}'

출력 예:

UID        PID  PPID  C STIME TTY          TIME CMD
root     23181 23137  0 15:33 pts/2    00:00:00 sudo su
vagrant  23136 23133  0 15:33 ?        00:00:01 sshd: vagrant@pts/2
root     23182 23181  0 15:33 pts/2    00:00:00 su
vagrant  23137 23136  0 15:33 pts/2    00:00:00 -bash
root      1041     1  0 Jan16 ?        00:00:00 /usr/sbin/sshd
root     23183 23182  0 15:33 pts/2    00:00:00 bash
root     12980     1  0 10:58 ?        00:00:01 /bin/bash /var/cfengine/bin/runalerts.sh
root         1     0  0 Jan16 ?        00:00:01 /sbin/init
root     23133  1041  0 15:33 ?        00:00:00 sshd: vagrant [priv]

위 목록에 나열된 상위 PID를 참고하세요.

관련 정보