实操Linux前后台任务

学过linux的童鞋们都知道,在命令行中启动某个任务有两种方式,一种是前台,一种是后台。 一般来说,对于短时任务,我们以前台方式运行,在这种方式下,任务运行结束后用户会再次回到命令行; 而对于长时任务,一般希望以后台方式运行,这样做的好处是,当用户退出命令行时并不影响任务运行。

方正ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

对于任务的管理,我们一般有如下几个需求:

将进程切换到前台

将进程切换到后台

查看后台任务

终止后台任务

为了演示这几个需求,我们搬出伟大的 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前后台任务
本文来源:http://www.csdahua.cn/qtweb/news32/286832.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网