본문 바로가기
OS 운영체제/LINUX

ps (프로세스 상태 명령어)

by yororing 2024. 4. 17.

00 개요

  • 리눅스는 여러 프로세스 (process)를 동시에 수행 시킬 수 있는 시스템
  • ps 명령어는 현재 프로세스 상태와 관련된 명령어

01 ps 명령어란

1. ps 정의

  • 'process status' 또는 'process state'의 약자

2. ps 명령어 기능

  • Linux 에서 현재 실행중인 프로세스에 관한 정보 출력  

3. ps 명령어 문법

ps [options]
  • options (옵션): 실행중인 프로세스 중 어떠한 정보를 출력할지 지정함

02 ps 명령어 옵션

1. 옵션 종류

  • 여러 개의 옵션을 함께 사용할 때는 - 기호는 한번만 써도 됨

1) simple process selection

종류 설명
-A 또는 -e all processes
이 옵션을 사용하지 않으면 현재 로그인된 shell에서 실행 중인 프로세스만 표시되기 때문에 대부분의 경우 -e 옵션을 사용
a all with tty(terminal), including other users
-a all processes except both session leaders and processes not associated with a terminal
-d all processes except session leaders
-deselect 또는 -N  all processes except those that fulfill the specified conditions (negates the selection)
g Really all, even session leaders.  This flag is obsolete and may be discontinued in a future release.  It is normally implied by the a flag, and is only useful when operating in the sunos4 personality.
T 또는 t  all processes associated with this terminal
r Restrict the selection to only running processes.
x include processes w/o controlling ttys
즉, 터미널에 연결되지 않은 프로세스도 포함하여 모든 프로세스 출력

2) process selection by list

  • These options accept a single argument in the form of a blank-separated or comma-separated list.  
  • They can be used multiple times.
  • 예: ps -p "1 2" -p 3,4
종류 설명
123 또는 -123 Identical to --pid 123
-C cmdlist Select by command name. This selects the processes whose executable name is given in cmdlist.
-G 또는 -Group grplist Select by real group ID (RGID) or name.  This selects the processes whose real group name or ID is in the grplist list. The real group ID identifies the group of the user who created the process, see getgid(2).
-g grplist Select by session OR by effective group name. Selection by session is specified by many standards, but selection by effective group is the logical behavior that several other operating systems use. This ps will select by session when the list is completely numeric (as sessions are). Group ID numbers will work only when some group names are also specified. See the -s and --group options.
--group grplist Select by effective group ID (EGID) or name.  This selects the processes whose effective group name or ID is in grplist.  The effective group ID describes the group whose file access permissions are used by the process (see getegid(2)).  The -g option is often an alternative to --group.
p 또는 -p 또는 --pid 
pidlist
Select by process ID.
--ppid pidlist Select by parent process ID.
This selects the processes with a parent process ID in pidlist.
That is, it selects processes that are children of those listed in pidlist.
q 또는 -q 또는
--quick-pid 
pidlist
Select by  process ID (quick mode).
This selects the processes whose process ID numbers appear in pidlist.
With this option ps reads the necessary info only for the pids listed in the pidlist and doesn't apply additional filtering rules.
The order of pids is unsorted and preserved. 
No additional selection options, sorting and forest type listings are allowed in this mode.
-s 또는 --sid sesslist Select by session ID.  This selects the processes with a session ID specified in sesslist.
ttylist Select by tty.
Nearly identical to -t and --tty, but can also be used with an empty ttylist to indicate the terminal associated with ps.
Using the T option is considered cleaner than using t with an empty ttylist.
-t ttylist Select by tty.
This selects the processes associated with the terminals given in ttylist.
Terminals (ttys, or screens for text output) can be specified in several forms: /dev/ttyS1, ttyS1, S1.
A plain "-" may be used to select processes not attached to any terminal.
--tty ttylist Select by terminal.  Identical to -t and t.
 U 또는 -u 또는 --user 
userlist
Select by effective user ID (EUID) or name.
This selects the processes whose effective user name or ID is in userlist.
The effective user ID describes the user whose file access permissions are used by the process (see geteuid(2)).
-U 또는 --User userlist Select by real user ID (RUID) or name.
It selects the processes whose real user name or ID is in the userlist list.  
The real user ID identifies the user who created the process, see getuid(2).

3) ouput format control

종류 설명
-c Show different scheduler info for the -l option.
--context  Display security context format (for SELinux)
-f Do full-format listing
프로세스를 실행한 UID, PID, PPID(부모 프로세스의 ID), command-line(프로세스를 실행할 당시의 커맨드라인)가 표시됨
→ 같은 이름의 프로세스가 여러 개 실행 중일 시 커맨드 라인으로 프로세스를 구분해야 하는 경우 용이하게 사용됨 (nginx 같은 경우)

This option can be combined with many other UNIX-style options to add additional columns. 
When used with -L, the NLWP (number of threads) and LWP (thread ID) columns will be added.
-F Extra full format.
--format
또는 o 또는 -o
format
Specify user-defined format.  
format is a single argument in the form of a blank-separated or comma-separated list, which offers a way to specify individual output columns.
The recognized keywords are described in the STANDARD FORMAT SPECIFIERS section below.
Headers may be renamed (ps -o pid,ruser=RealUser -o comm=Command) as desired.
If all column headers are empty (ps -o pid= -o comm=) then the header line will not be output.
Column width will increase as needed for wide headers; this may be used to widen up columns such as WCHAN (ps -o pid,wchan=WIDE-WCHAN-COLUMN -o comm).
Explicit width control (ps opid,wchan:42,cmd) is offered too.
The behavior of ps -o pid=X,comm=Y varies with personality; output may be one column named "X,comm=Y" or two columns named "X" and "Y". 
Use multiple -o options when in doubt.  Use the PS_FORMAT environment variable to specify a default as desired; DefSysV and DefBSD are macros that may be used to choose the default UNIX or BSD columns.
j BSD job control format.
-j Jobs format
l Display BSD long format.
-l  Long format.  The -y option is often useful with this.
-M 또는 Z Add a column of security data.  Identical to Z (for SELinux).
 O format is preloaded o (overloaded).
The BSD O option can act like -O (user-defined output format with some common fields predefined) or can be used to specify sort order.
Heuristics are used to determine the behavior of this option.
To ensure that the  desired behavior is obtained (sorting or formatting), specify the option in some other way (e.g.  with -O or --sort).
When used as a formatting option, it is identical to -O, with the BSD personality.
-O format Like -o, but preloaded with some default columns.  
Identical to -o pid,format,state,tname,time,command or -o pid,format,tname,time,cmd, see -o below.
s signal format
u user-oriented format 사용자 친화적 형식
각 프로세스의 사용자 관련 정보 표시
출력값:
- USER    PID    %CPU    %MEM (메모리 사용률)
- VSZ (가상 메모리 크기, KB 단위)
- RSS (실제 메모리 사용량, KB 단위)
- TTY (터미널 타입)
- STAT (프로세스 상태)
- START (프로세스 시작 시간/날짜)
- TIME (CPU 시간 사용량)
- COMMAND (실행 중인 명령어)
v virtual memory format
X Register format
-y Do not show flags; show rss in place of addr.
This option can only be used with -l.

4) output modifiers

종류 설명
c Show the true command name.
This is derived from the name of the executable file, rather than from the argv value.
Command arguments and any modifications to them are thus not shown.
This option effectively turns the args format keyword into the comm format keyword; it is useful with the -f format option and with the various BSD-style format options, which all normally display the command arguments.  
See the -f option, the format keyword args, and the format keyword comm.
--cols 또는 --columns
또는 --width n
Set screen width.
--cumulative Include some dead child process data (as a sum with the parent).
e Show the environment after the command.
f ASCII art process hierarchy (forest).
--forest  ASCII art process tree.
h No header.  (or, one header per screen in the BSD personality).
The h option is problematic.
Standard BSD ps uses this option to print a header on each page of output, but older Linux ps uses this option to totally disable the header.
This version of ps follows the Linux usage of not printing the header unless the BSD personality has been selected, in which case it prints a header on each page of output.
Regardless of the current personality, you can use the long options --headers and --no-headers to enable printing headers each page or disable headers entirely, respectively.
-H Show process hierarchy (forest).
--headers  Repeat header lines, one per page of output.
k 또는 --sort spec Specify sorting order.
Sorting syntax is [+|-]key[,[+|-]key[,...]].
Choose a multi-letter key from the STANDARD FORMAT SPECIFIERS section.
The "+" is optional since default direction is increasing numerical or lexicographic order.  
예)
                      ps jaxkuid,-ppid,+pid
                      ps axk comm o comm,args
                      ps kstart_time -ef
--lines 또는 --rows n Set screen height.
-n 또는 N namelist Set namelist file.
The namelist file is needed for a proper WCHAN display, and must match the current Linux kernel exactly for correct output.
Without this option, the default search path for the namelist is:
                      $PS_SYSMAP
                      $PS_SYSTEM_MAP
                      /proc/*/wchan
                      /boot/System.map-$(uname -r)
                      /boot/System.map
                      /lib/modules/$(uname -r)/System.map
                      /usr/src/linux/System.map
                      /System.map
n Numeric output for WCHAN and USER (including all types of UID and GID).
--no-headers Print no header line at all.
--no-heading is an alias for this option.
order Sorting order (overloaded).
The BSD O option can act like -O (user-defined output format with some common fields predefined) or can be used to specify sort order.
Heuristics are used to determine the behavior of this option.
To ensure that the desired behavior is obtained (sorting or formatting), specify the option in some other way (e.g.  with -O or --sort).

For sorting, obsolete BSD O option syntax is O[+|-]k1[,[+|-]k2[,...]].
It orders the processes listing according to the multilevel sort specified by the sequence of one-letter short keys k1,k2, ...  described in the OBSOLETE SORT KEYS section below.
The "+" is currently optional, merely re-iterating the default direction on a key, but may help to distinguish an O sort from an O format.
The "-" reverses direction only on the key it precedes.
S Sum up some information, such as CPU usage, from dead child processes into their parent.
This is useful for examining a system where a parent process repeatedly forks off short-lived children to do work.
w 또는 -w Wide output. Use this option twice for unlimited width.

5) thread display

종류 설명
H Show threads as if they were processes.
-L Show threads, possibly with LWP and NLWP columns.
m 또는 -m  Show threads after processes.
-T Show threads, possibly with SPID column.

6) other information

종류 설명
--help section Print a help message.
The section argument can be one of simple, list, output, threads, misc or all.
The argument can be shortened to one of the underlined letters as in: s|l|o|t|m|a.
--info Print debugging info.
L List all format specifiers.
V 또는 -V 또는 --version Print the procps-ng version.

2. 자주 사용하는 옵션 유형

To see every process on the system using standard syntax:

# ps -e
# ps -ef
# ps -eF
# ps -ely

To see every process on the system using BSD syntax:

# ps ax
# ps axu
# ps aux
  • ps aux:
    • a: all processes with tty (terminal, including other users)
    • u: user-oriented format
    • x: include processes w/o controlling ttys

현재 사용자와 관련된 프로세스의 목록 출력:

# ps ux

예)
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0 129808  7212 ?        Ss   Jul19   0:57 /usr/lib/systemd/systemd --switched-root --system --deserialize 22
root         2  0.0  0.0      0     0 ?        S    Jul19   0:00 [kthreadd]
root         5  0.0  0.0      0     0 ?        S<   Jul19   0:00 [kworker/0:0H]
root     28101  0.0  0.0 116480  3220 pts/8    Ss   09:38   0:00 /bin/bash --init-file /root/.vscode-server/bin/0ee08df0cf4527e40edc9aa28f4b5bd38bbff2b2/out/vs/workbench/contrib/terminal/browser/media/shellIntegration-b
root     28317  0.0  0.0 182908  4696 pts/8    S+   09:39   0:00 ssh root@10.0.0.132
root     30614  0.0  0.0  32180  2960 ?        S<s  Jul22   0:00 /sw/LSF/10.1/linux2.6-glibc2.3-x86_64/etc/res
  • ps ux:
    • u: user-oriented format
    • x: processes w/o controlling ttys

To print a process tree:

# ps -ejH
# ps axjf

To get info about threads:

# ps -eLf
# ps axms

To get security info:

# ps -eo euser,ruser,suser,fuser,f,comm,label
# ps axZ
# ps -eM

To see every process running as root (real & effective ID) in user format:

# ps -U root -u root u

To see every process with a user-defined format:

# ps -eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:14,comm
# ps axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm
# ps -Ao pid,tt,user,fname,tmout,f,wchan

Print only the process IDs of syslogd:

# ps -C syslogd -o pid=

Print only the name of PID 42:

# ps -q 42 -o comm=

03 ps 명령어 출력 항목

종류
설명
USER (BSD)
UID (System V)
프로세스 소유자의 이름 (프로세스를 실행 중인 사용자 이름)
PID
프로세스 ID
PPID
부모 프로세스의 PID
%CPU
CPU 사용 비율의 추정치 (BSD) (CPU 사용률)
%MEM
Memory 사용 비율의 추정치(BSD) (메모리 사용률)
VSZ
가상 메모리 사용량/크기 (KB 단위 또는 페이지 단위)
RSS
실제 메모리 사용량 (KB 단위)
TTY
프로세스와 연결된 터미널 (터미널 타입)
S (System V)
STAT (BSD)
현재 프로세스의 상태 코드
TIME
총 CPU 사용 시간
COMMAND
프로세스의 실행 명령행 (실행 중인 명령어)
STIME
START
프로세스 시작 시간 또는 날짜
C (System V)
CP (BSD)
짧은 기간 동안의 CPU 사용률
F
플래그
PRI
실제 실행 우선순위
NI
nice 우선순위 번호

참조

  1. (개요, ps 명령어란, ps 명령어 출력 항목) https://blog.naver.com/tmk0429/222318530824 
  2. (ps 명령어 옵션) man ps
  3. https://gracefulprograming.tistory.com/126