进程管理 #

一、后台执行 #

bash
#!/bin/bash

# 后台执行
command &

# nohup执行
nohup command &

# 查看后台任务
jobs

# 前台恢复
fg %1

# 后台恢复
bg %1

二、进程监控 #

bash
#!/bin/bash

# 查看进程
ps aux
ps -ef

# 查找进程
pgrep nginx
ps aux | grep nginx

# 进程树
pstree

# 实时监控
top
htop

三、进程控制 #

bash
#!/bin/bash

# 发送信号
kill PID
kill -9 PID      # 强制终止
kill -HUP PID    # 重新加载

# 按名称终止
pkill nginx
killall nginx

# 等待进程
wait PID
wait $!

四、实战示例 #

bash
#!/bin/bash

# 守护进程
run_daemon() {
    while true; do
        # 执行任务
        echo "$(date): 执行任务"
        sleep 60
    done
}

# 启动守护进程
run_daemon &

# 监控脚本
monitor_process() {
    local process_name="$1"
    
    while true; do
        if ! pgrep "$process_name" > /dev/null; then
            echo "进程 $process_name 未运行,重启..."
            # 重启逻辑
        fi
        sleep 10
    done
}

下一步 #

你已经掌握了进程管理,接下来让我们学习 信号处理

最后更新:2026-03-27