Skip to content
xiaoyang 的头像xiaoyang发布于 2025-03-031,920 字阅读约 6 分钟浏览加载中

Linux 进程管理 ​

本章全面介绍 Linux 进程管理,包括进程与线程的区别、前后台进程管理、进程状态与信号、systemd 进程管理,以及定时任务管理(crontab、at、anacron)。


1. 什么是进程?进程 vs 线程 ​

(1)进程(Process) ​

进程是计算机中执行的程序实例,每个进程都有自己的内存空间、文件描述符和资源。进程是独立的,进程之间不能直接共享内存。

查看当前系统的进程数:

bash
ps aux | wc -l

(2)线程(Thread) ​

线程是进程中的执行单元,一个进程可以包含多个线程(多线程)。线程共享进程的资源(如内存、文件句柄),但有独立的执行栈和 CPU 寄存器。

多线程示例:

c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void* thread_func(void* arg) {
    printf("Thread %ld is running\n", (long)arg);
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, (void*)1);
    pthread_join(tid, NULL);
    return 0;
}

编译并运行:

bash
gcc -pthread thread.c -o thread
./thread

2. 前台进程与后台进程(&,nohup,jobs,bg,fg) ​

(1)后台运行进程 ​

使用 & 让进程在后台运行:

bash
ping google.com > ping.log &

(2)查看后台进程 ​

bash
jobs -l

(3)将进程转入后台 ​

bash
Ctrl + Z  # 暂停前台进程
bg %1     # 让任务号 1 的进程在后台继续运行

(4)将后台进程恢复到前台 ​

bash
fg %1

(5)使用 nohup 保持进程运行 ​

nohup 让进程在退出终端后仍然运行:

bash
nohup my_script.sh &
disown -h %1  # 让任务号 1 的进程脱离终端

3. 进程状态与信号(ps, top, kill, nice, renice) ​

(1)查看进程信息 ​

bash
ps aux  # 查看所有进程
ps -ef  # 以不同格式显示进程

(2)监控进程 ​

bash
top  # 实时监控进程
htop  # 更美观的进程监控工具(需安装)

(3)终止进程 ​

bash
kill -9 <PID>  # 强制杀死进程
kill -15 <PID> # 发送 SIGTERM 信号(优雅终止)

(4)调整进程优先级 ​

nice 设置进程优先级:

bash
nice -n 10 myscript.sh

renice 调整运行中的进程优先级:

bash
renice -n 5 -p <PID>

4. systemd 进程管理(systemctl,service) ​

(1)启动、停止、重启服务 ​

bash
systemctl start nginx
systemctl stop nginx
systemctl restart nginx

(2)查看服务状态 ​

bash
systemctl status nginx

(3)启用/禁用开机启动 ​

bash
systemctl enable nginx
systemctl disable nginx

(4)使用 service 命令管理进程 ​

bash
service nginx status

5. 定时任务管理(crontab, at, anacron) ​

(1)使用 crontab ​

bash
crontab -e  # 编辑当前用户的定时任务
crontab -l  # 查看当前用户的定时任务

示例:每天凌晨 2 点执行备份:

bash
0 2 * * * /usr/bin/backup.sh

(2)使用 at ​

bash
echo "echo Hello > /tmp/hello.txt" | at now + 5 minutes

(3)使用 anacron(适用于非 24 小时运行的机器) ​

编辑 /etc/anacrontab:

ini
1   5   backup-job   /usr/bin/backup.sh
DISCUSSION

评论区

欢迎分享你的思考、补充或问题。

基于 VitePress 搭建