背景
Linux下的fg和bg命令是进程的前后台调度命令,即将指定号码(非进程号)的命令进程放到前台或后台运行。比如一个需要长时间运行的命令,我们就希望把它放入后台,这样就不会阻塞当前的操作;而一些服务型的命令进程我们则希望能把它们长期运行于后台。
命令
进程前后台操作用到以下命令:
# 在前台结束进程 Control+C # 在前台暂停进程 Control+Z # 查看后台执行的进程 查看进程号码 jobs # 运行命令时,在命令末尾加上&可让命令在后台执行 & # 将命令进程号码为N的命令进程放到前台执行 fg processNum # 或者 %processNum # 将命令进程号码为N的命令进程放到后台执行 bg processNum
实操
我们在操作系统上实际演练一下,这里用的环境是MacOS Catlina + zsh。
启动一个需要长时间执行的程序,我们这里选择ping,每隔一定时间向特定网址发送数据包并且输出详细信息。
1. 启动ping,一段时间后Ctrl + Z 暂停程序
yanximin@B000000120095D ~ % ping www.baidu.com PING www.a.shifen.com (61.135.169.125): 56 data bytes 64 bytes from 61.135.169.125: icmp_seq=0 ttl=55 time=0.995 ms 64 bytes from 61.135.169.125: icmp_seq=1 ttl=55 time=1.151 ms 64 bytes from 61.135.169.125: icmp_seq=2 ttl=55 time=1.005 ms 64 bytes from 61.135.169.125: icmp_seq=3 ttl=55 time=1.129 ms ^Z zsh: suspended ping www.baidu.com
2. jobs 查看后台程序
yanximin@B000000120095D ~ % jobs [1] + suspended ping www.baidu.com
3. fg 把程序放在前台恢复运行
yanximin@B000000120095D ~ % fg %1 [1] + continued ping www.baidu.com 64 bytes from 61.135.169.125: icmp_seq=4 ttl=55 time=1.350 ms 64 bytes from 61.135.169.125: icmp_seq=5 ttl=55 time=1.070 ms 64 bytes from 61.135.169.125: icmp_seq=6 ttl=55 time=1.160 ms 64 bytes from 61.135.169.125: icmp_seq=7 ttl=55 time=1.108 ms
另外 这里也可以直接用%1,不用加fg
yanximin@B000000120095D ~ % %1 [1] + continued ping www.baidu.com 64 bytes from 61.135.169.125: icmp_seq=16 ttl=55 time=1.114 ms 64 bytes from 61.135.169.125: icmp_seq=17 ttl=55 time=1.277 ms
4. 再使用Ctrl + Z 暂停程序,然后使用bg, 放在后台继续运行
yanximin@B000000120095D ~ % 64 bytes from 61.135.169.125: icmp_seq=18 ttl=55 time=1.112 ms 64 bytes from 61.135.169.125: icmp_seq=19 ttl=55 time=1.017 ms 64 bytes from 61.135.169.125: icmp_seq=20 ttl=55 time=1.318 ms 64 bytes from 61.135.169.125: icmp_seq=21 ttl=55 time=1.188 ms 64 bytes from 61.135.169.125: icmp_seq=22 ttl=55 time=0.952 ms 64 bytes from 61.135.169.125: icmp_seq=23 ttl=55 time=0.913 ms 64 bytes from 61.135.169.125: icmp_seq=24 ttl=55 time=0.949 ms 64 bytes from 61.135.169.125: icmp_seq=25 ttl=55 time=1.167 ms
这里没有重定向标准输出,所以即使是后台执行的,也会往终端打印。可以使用nohup和重定向,来做到真正的后台执行
nohup ping www.baidu.com >log.txt 2>error.txt &
5. 最后使用ctrl + C 来结束进程
PING www.a.shifen.com (61.135.169.125): 56 data bytes 64 bytes from 61.135.169.125: icmp_seq=0 ttl=55 time=1.120 ms 64 bytes from 61.135.169.125: icmp_seq=1 ttl=55 time=0.981 ms 64 bytes from 61.135.169.125: icmp_seq=2 ttl=55 time=1.214 ms 64 bytes from 61.135.169.125: icmp_seq=3 ttl=55 time=1.003 ms 64 bytes from 61.135.169.125: icmp_seq=4 ttl=55 time=1.173 ms ^C --- www.a.shifen.com ping statistics --- 5 packets transmitted, 5 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 0.981/1.098/1.214/0.092 ms