nohup命令可以将你要执行的程序放在后台运行,即使退出shell命令行也不会停止。
格式:nohup command &
nohup的使用示例:
[root@test www]# nohup php ./chat_server.php > chat_server.log 2>&1 &
[1] 24073
意思是后台运行这个php脚本,并将标准输出和错误输出到chat_server.log文件中,如果不加输出重定向,则程序输出默认将写入到当前文件夹的nohup.out文件中。
然后我们看看这个脚本是否真的在执行
[root@test www]# ps -ef|grep chat_server
root 24073 23954 0 14:29 pts/4 00:00:00 php ./chat_server.php
root 24074 24073 0 14:29 pts/4 00:00:00 php ./chat_server.php
root 24076 24074 0 14:29 pts/4 00:00:00 php ./chat_server.php
root 24079 23954 0 14:29 pts/4 00:00:00 grep --color=auto chat_server
使用jobs命令查看通过nohup命令开启的后台程序
[root@test www]# jobs
[1]+ Running nohup php ./chat_server.php > chat_server.log 2>&1 &
使用fg命令将后台任务调到前台 fg %number 然后可以ctrl+c停止 ctrl+z暂停
[root@test www]# fg %1
nohup php chat_server.php > chat_server.log 2>&1
^Z
[1]+ Stopped nohup php chat_server.php > chat_server.log 2>&1
在查看任务,任务已经暂停
[root@test www]# jobs
[1]+ Stopped nohup php chat_server.php > chat_server.log 2>&1
使用bg %number使暂停的任务开始执行
[root@test www]# bg %1
[1]+ nohup php chat_server.php > chat_server.log 2>&1 &
此时查看任务已经在执行了
[root@test www]# jobs
[1]+ Running nohup php chat_server.php > chat_server.log 2>&1 &
将后台任务停止
[root@test www]# fg %1
nohup php ./chat_server.php > chat_server.log 2>&1
^C
此时已经没有任务了
[root@test www]# ps -ef|grep chat_server
root 24081 23954 0 14:29 pts/4 00:00:00 grep --color=auto chat_server
[root@test www]# jobs
评论
2