shell——进程控制
1. 前台进程后台进程
前台进程:运行期间独占终端。
1.1 如何避免长耗时进程占用终端?
如 编译 kernel 时,将 make 放到后台,并重定向 标准输出 标准错误
[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[1] 4167
1.2 如何查看后台进程运行情况?
[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[1] 4167 # 将一个进程放到后台后,会显示 [任务号] 进程号,每个终端有自己的任务号分配。
[root@ifw8 polarssl-1.2.17]# make 1>output.txt 2>&1 &
[2] 4849 # 第二个任务
# jobs 查看后台进程状态,
# Done 表示运行成功返回
# Exit 表示错误返回
[root@ifw8 polarssl-1.2.17]# jobs
[1]- Exit make > output.txt 2>&1 &
[2]+ Running make > output.txt 2>&1 &
- 表示 fg 命令默认切换的任务
- 表示 fg 命令切换替补
1.3 如何让后台进程 接受 用户输入?
后台进程的标准输入没有关联终端,所以当需要用户输入时,会一直阻塞。
为解决这个问题,可以将后台进程切换为前台进程。
[root@ifw8 polarssl-1.2.17]# cat &
[1] 6007
[root@ifw8 polarssl-1.2.17]# jobs
[1]+ Stopped cat
[root@ifw8 polarssl-1.2.17]# fg %1
cat
adf
adf
若提前知道 进程需要的输入,可以用 重定向标准输入 到文件。避免 使用 fg
1.4 如何将以运行前台进程 切换到后台?
用 ctrl-z 让前台进程挂起,再用 bg %tid 让其切换到后台运行。
[root@ifw8 polarssl-1.2.17]# make 1>./output.txt 2>&1
^Z
[1]+ Stopped make > ./output.txt 2>&1
[root@ifw8 polarssl-1.2.17]# jobs
[1]+ Stopped make > ./output.txt 2>&1
[root@ifw8 polarssl-1.2.17]# bg %1
[1]+ make > ./output.txt 2>&1 &
[root@ifw8 polarssl-1.2.17]# jobs
[1]+ Running make > ./output.txt 2>&1 &
使用 fg %tid ,可以让 挂起进程 返回前台继续运行。
1.5 如何 避免退出终端 导致 后台进程退出?
默认情况,退出终端,终端的子进程都会被杀死。导致后台进程被杀死。
使用 nohup 避免这个情况。
nohup 启动的进程都是后台进程,当终端退出,nohup 的进程的父进程变成 init 进程。
若没有重定向标准输出,默认重定向到 当前目录下 nohup.out
若没有重定向标准输入,默认重定向到 /dev/null
[root@ifw8 polarssl-1.2.17]# nohup make &
[1] 6888
[root@ifw8 polarssl-1.2.17]# nohup: ignoring input and appending output to `nohup.out'
[root@ifw8 polarssl-1.2.17]# ps -aux |grep make
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root 6888 0.0 0.0 4200 884 ? S 09:36 0:00 make
[root@ifw8 polarssl-1.2.17]# tail -f nohup.out
Generate test_suite_gcm.decrypt_128.c
CC test_suite_gcm.decrypt_128.c
Generate test_suite_gcm.decrypt_192.c
1.6 重要提示
- 运行后台进程使用重定向操作时,一定要把后台运行符号& 放到最后。
- 使用 fg bg 时,任务号前一定加%
- 后台进程随终端退出而被杀死,应该使用nohup运行后台进程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?