码迷,mamicode.com
首页 > 其他好文 > 详细

如何让程序在后台执行

时间:2015-11-23 23:11:05      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

示例:查看系统负载的脚本

#!/bin/sh

while true
do
  uptime >/tmp/uptime.log
  sleep 1
done
[root@lamp scripts]# tail -f /tmp/uptime.log 
 21:37:26 up  5:49,  2 users,  load average: 0.00, 0.00, 0.00
tail: /tmp/uptime.log: file truncated
 21:37:27 up  5:49,  2 users,  load average: 0.00, 0.00, 0.00
tail: /tmp/uptime.log: file truncated
 21:37:28 up  5:49,  2 users,  load average: 0.00, 0.00, 0.00
tail: /tmp/uptime.log: file truncated

 

当我们执行该脚本的时候:

会出现在登录的界面卡顿的情况,无法执行其他的命令,此时如果出现网络中断(用户掉线)任务就会停止;所以我们在执行的时候会加上“&”符号,意为在后台执行,当用户退出的时候该任务仍会执行。

 

[root@lamp scripts]# sh test.sh  



^C
[root@lamp scripts]# sh test.sh &
[1] 25352
[root@lamp scripts]# 

 

但是,当我们想停止任务的时候怎么办?

[root@lamp scripts]# sh test.sh &
[1] 25352
[root@lamp scripts]# jobs
[1]+  Running                 sh test.sh &
[root@lamp scripts]# fg 1    //为任务号
sh test.sh
^C
[root@lamp scripts]# 

 

有时候我们想将在前台执行的任务转为后台执行怎么办?

[root@lamp scripts]# sh test.sh  

^Z
[1]+  Stopped                 sh test.sh
[root@lamp scripts]# bg 1         //1为任务号
[1]+ sh test.sh &
[root@lamp scripts]# jobs
[1]+  Running                 sh test.sh &
[root@lamp scripts]# 

 

 

让程序后台执行的几种方法:

  1.sh test.sh &

  2.screen

  3.nohup test.sh &

 

如何让程序在后台执行

标签:

原文地址:http://www.cnblogs.com/along1226/p/4989797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!