linux任务前台转后台/后台转前台运行

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

举例来说, run.sh脚本内容如下

#!/bin/bash
while true; do
    sleep 1
    echo "hello world"

前台运行:

$ bash run.sh           
hello world
hello world
hello world
hello world

后台运行:

$ nohup bash  run.sh 2>&1 &                                                                     
[1] 31520
nohup: ignoring input and appending output to 'nohup.out'

$ tailf nohup.out 
hello world
hello world
hello world
hello world
hello world
hello world

其中31520表示作业id。如果不加nohup, 当终端退出时,run.sh对应的进程会收到SIGHUP信号,而进程对SIGHUP信号的默认处理方式是终止,这显然不是我们想要的。而加上nohup之后,run.sh对应的进程会忽略SIGHUP信号,即终端退出并不影响进程继续运行.

前台运行转后台

很多情况下,我们并不知晓某个任务会运行多久,因此一般在前台运行该任务。如果发现该任务一时半会完成不了,能不能将它从前台运行转到后台?答案是可以,举例说明如何操作:

首先在前台运行run.sh

$ bash run.sh 
hello world
hello world
hello world

输入ctrl + z 将该前台任务挂起

^Z
[1]  + 32295 suspended  bash run.sh

运行jobs命令,查看任务号(可以看到run.sh对应的任务号是1)

$ jobs                                                                                                  
[1]  + suspended  bash run.sh

运行bg命令  %任务号,将任务从前台转到后台

bg %1

后台运行转前台

既然任务可以从前台转后台,那反过来从后台转前台是否可行呢?答案是可以的 首先以后台运行run.sh 

$ nohup bash  run.sh 2>&1 & 
[1] 482
nohup: ignoring input and appending output to 'nohup.out'

查看后台任务

$ jobs
[1]  + running    nohup bash run.sh 2>&1

运行fg命令,将任务从后台转到前台

$ fg %1                    
[1]  + 482 running    nohup bash run.sh 2>&1
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巫嘎嘎

坚持不易,求打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值