在 Linux 中创建进程主要通过以下方式实现:
command [args]
例如:
ls -l # 创建 ls 进程
vim file # 创建 vim 进程
command [args] &
例如:
python script.py & # 后台运行 Python 脚本
nohup
(忽略挂起信号,退出终端仍运行):
bash
nohup command [args] &
screen
/tmux
(会话管理):
bash
screen -S session_name
command [args] # 在 screen 会话中运行
systemd
(现代 Linux):
bash
systemctl start service_name # 启动服务进程
service
(旧版系统):
bash
service service_name start
c
#include <unistd.h>
pid_t pid = fork(); // 创建子进程
if (pid == 0) {
execl("/bin/ls", "ls", NULL); // 子进程替换为 ls
}
命令/符号 | 作用 |
---|---|
& |
后台运行 |
nohup |
防止进程因终端退出而终止 |
fork() |
系统调用创建子进程 |
exec |
替换当前进程映像 |
ps aux # 查看所有进程
jobs # 查看当前终端的后台进程
pstree # 树状显示进程关系
根据需求选择合适的方式:
- 临时任务 → 直接运行或 &
- 长期运行 → nohup
/screen
/systemd
- 编程控制 → fork()
+exec()