导读 | 我们知道,Linux 是一个多任务的操作系统,也就是说,在同一时间,系统可以运行多个任务。在带界面的 Linux 发行版下,我们可以很轻松通过鼠标来进行多任务的切换。但是,在终端下,操作几乎是脱离鼠标的,如何进行任务的前后台管理呢? |
对于任务的管理,我们一般有如下几个需求:
将进程切换到前台
将进程切换到后台
查看后台任务
终止后台任务
为了演示这几个需求,我们搬出伟大的 Hello World 程序:
root@jaking-virtual-machine:~# ls -l #这三个源码相同 total 12 -rwxr-xr-x 1 root root 70 Feb 21 17:25 HelloWorld1.sh -rwxr-xr-x 1 root root 70 Feb 21 17:25 HelloWorld2.sh -rwxr-xr-x 1 root root 70 Feb 21 17:26 HelloWorld3.sh root@jaking-virtual-machine:~# cat HelloWorld1.sh #!/bin/bash while true do echo "Hello World!" sleep 1 done
开启后台任务
root@jaking-virtual-machine:~# ./HelloWorld1.sh > test1.txt & [1] 65139 root@jaking-virtual-machine:~# ./HelloWorld2.sh > test1.txt & [2] 65145 root@jaking-virtual-machine:~# ./HelloWorld3.sh > test1.txt & [3] 65155
jobs -l 查看后台任务
root@jaking-virtual-machine:~# jobs -l [1] 65139 Running ./HelloWorld1.sh > test1.txt & [2]- 65145 Running ./HelloWorld2.sh > test1.txt & [3]+ 65155 Running ./HelloWorld3.sh > test1.txt &
fg 把指定的后台任务调到前台
root@jaking-virtual-machine:~# fg %2 ./HelloWorld2.sh > test1.txt ^Z #Ctrl + Z将前台任务切到后台并停止运行 [2]+ Stopped ./HelloWorld2.sh > test1.txt root@jaking-virtual-machine:~# jobs -l [1] 65139 Running ./HelloWorld1.sh > test1.txt & [2]+ 65145 Stopped ./HelloWorld2.sh > test1.txt [3]- 65155 Running ./HelloWorld3.sh > test1.txt &
bg 使后台停止运行的任务重新运行
root@jaking-virtual-machine:~# bg %2 [2]+ ./HelloWorld2.sh > test1.txt & root@jaking-virtual-machine:~# jobs -l [1] 65139 Running ./HelloWorld1.sh > test1.txt & [2]- 65145 Running ./HelloWorld2.sh > test1.txt & [3]+ 65155 Running ./HelloWorld3.sh > test1.txt &
kill 杀掉后台进程
root@jaking-virtual-machine:~# kill 65145 root@jaking-virtual-machine:~# jobs -l [1] 65139 Running ./HelloWorld1.sh > test1.txt & [2]- 65145 Terminated ./HelloWorld2.sh > test1.txt [3]+ 65155 Running ./HelloWorld3.sh > test1.txt & root@jaking-virtual-machine:~# kill %3 root@jaking-virtual-machine:~# jobs -l [1]- 65139 Running ./HelloWorld1.sh > test1.txt & [2]- 65145 Terminated ./HelloWorld2.sh > test1.txt [3]+ 65155 Terminated ./HelloWorld3.sh > test1.txt
本文原创地址://q13zd.cn/front-background-tasks.html编辑:public,审核员:逄增宝