Chuyển tới nội dung chính

Quản lý Process


Vòng đời Process

Trạng tháiKý hiệuÝ nghĩa
RunningRĐang chạy hoặc chờ CPU
SleepingSChờ I/O, có thể interrupt
Disk WaitDChờ I/O hardware, không interrupt được
StoppedTBị dừng (Ctrl+Z hoặc SIGSTOP)
ZombieZĐã exit nhưng parent chưa cleanup

Xem Process

ps — Process Snapshot

ps                          # chỉ process trong terminal hiện tại
ps aux # TẤT CẢ process (BSD style — phổ biến nhất)
ps -ef # TẤT CẢ process (UNIX style)
ps aux | grep nginx # tìm process nginx
ps -p 1234 # xem process theo PID
ps -u sontn # process của user sontn
ps --forest # hiển thị dạng cây (parent-child)
# Đọc output ps aux:
# USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
# root 1 0.0 0.1 225880 9128 ? Ss Jan10 0:05 /sbin/init
# nginx 123 0.1 0.5 56040 20480 ? S 10:00 0:02 nginx: worker
#
# VSZ = Virtual memory size
# RSS = Resident Set Size (RAM thực sự dùng)
# STAT = Trạng thái: S=sleeping, R=running, Z=zombie, D=disk wait
# s=session leader, l=multi-threaded, +=foreground

top / htop — Real-time Monitor

top                         # interactive monitor
top -u sontn # chỉ process của user
top -p 1234,5678 # theo dõi PID cụ thể
top -bn1 # batch mode, 1 lần (dùng trong script)

Phím tắt trong top:

PhímChức năng
PSort theo CPU
MSort theo Memory
kKill process (nhập PID)
1Hiện từng CPU core
qThoát
hXem help
# htop — giao diện đẹp hơn, cần cài
sudo apt install htop
htop
htop -u sontn

pgrep / pidof — Tìm PID

pgrep nginx                 # PID của tất cả nginx process
pgrep -l nginx # PID + tên process
pgrep -u sontn python # python process của user sontn
pidof nginx # tương tự pgrep
pstree # cây process toàn hệ thống
pstree -p sontn # cây process của user

Điều tra Process sâu hơn

# Thông qua /proc filesystem
ls -la /proc/1234/ # thông tin process PID 1234
cat /proc/1234/cmdline # lệnh khởi chạy
cat /proc/1234/status # state, memory, uid...
cat /proc/1234/environ # biến môi trường
ls -la /proc/1234/fd/ # file descriptors đang mở

# lsof — List Open Files
lsof -p 1234 # tất cả file process đang mở
lsof -u sontn # file user sontn đang mở
lsof -i :80 # process nào đang dùng port 80
lsof -i :80 -i :443 # port 80 và 443
lsof +D /var/log/ # process nào đang dùng thư mục này

Gửi Signal cho Process

# kill — gửi signal theo PID
kill 1234 # SIGTERM (15) — yêu cầu dừng graceful
kill -9 1234 # SIGKILL — buộc dừng ngay (không ignore được)
kill -15 1234 # SIGTERM tường minh
kill -HUP 1234 # SIGHUP — reload config (nginx, sshd)
kill -STOP 1234 # tạm dừng process
kill -CONT 1234 # tiếp tục process đã dừng

# killall / pkill — kill theo tên
killall nginx # kill TẤT CẢ process tên nginx
pkill -9 python # kill tất cả python process
pkill -u sontn # kill tất cả process của user sontn
pkill -f "gunicorn app" # kill theo full command line
SIGTERM trước, SIGKILL sau

Luôn thử kill <PID> (SIGTERM) trước để process có thời gian cleanup graceful (đóng connection, flush buffer, ghi log). Chỉ dùng kill -9 khi SIGTERM không hiệu quả sau vài giây.

SignalSốÝ nghĩaCó thể ignore?
SIGHUP1Reload config / disconnect terminal
SIGINT2Ctrl+C
SIGKILL9Force killKhông
SIGTERM15Graceful stop
SIGSTOP19Pause processKhông
SIGCONT18Continue paused process

Foreground, Background và Jobs

# Chạy lệnh ở background
./long_script.sh & # chạy background, thoát ngay
nohup ./script.sh > output.log & # background + không bị kill khi logout

# Quản lý jobs trong shell
jobs # liệt kê jobs trong shell hiện tại
jobs -l # kèm PID
fg # đưa job gần nhất về foreground
fg %2 # đưa job số 2 về foreground
bg # tiếp tục job đang pause ở background
bg %2 # tiếp tục job số 2

# Ctrl+Z → dừng process hiện tại → bg để tiếp tục ở background
# tmux — terminal multiplexer (persistent session)
tmux new -s deploy # tạo session tên "deploy"
tmux attach -t deploy # kết nối lại session
tmux ls # liệt kê session
# Ctrl+B, D → detach (session vẫn chạy dù logout SSH)

systemd — Quản lý Services

systemd là init system hiện đại, chạy với PID 1, quản lý toàn bộ vòng đời service.

systemctl — Điều khiển service

# Xem trạng thái
systemctl status nginx # trạng thái service chi tiết
systemctl is-active nginx # active / inactive
systemctl is-enabled nginx # enabled / disabled

# Điều khiển service
sudo systemctl start nginx # khởi động
sudo systemctl stop nginx # dừng
sudo systemctl restart nginx # dừng rồi khởi động lại
sudo systemctl reload nginx # reload config (không restart process)
sudo systemctl enable nginx # tự động start khi boot
sudo systemctl disable nginx # không tự start khi boot
sudo systemctl enable --now nginx # enable + start ngay

# Liệt kê service
systemctl list-units --type=service # service đang active
systemctl list-units --type=service --all # tất cả service
systemctl list-unit-files --type=service # trạng thái enabled/disabled

journalctl — Xem log của systemd

journalctl -u nginx                             # log của nginx service
journalctl -u nginx -f # follow real-time
journalctl -u nginx -n 100 # 100 dòng cuối
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since "2024-01-15 10:00" --until "2024-01-15 11:00"
journalctl -u nginx -p err # chỉ error level trở lên
journalctl -xe # lỗi gần nhất với context
journalctl -k # kernel log (như dmesg)
journalctl --disk-usage # dung lượng journal đang chiếm

Tạo systemd service tùy chỉnh

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=ubuntu
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/start.sh
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
# Sau khi tạo/sửa unit file
sudo systemctl daemon-reload # reload systemd để nhận file mới
sudo systemctl enable --now myapp