Linux前后台任务实用操作

导读我们知道,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

原文地址:https://www.linuxprobe.com/front-background-tasks.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值