学过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
以上就是良许教程网为各位朋友分享的Linux系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !