让进程在Linux后台可靠运行的几种方法

我们经常会碰到这样的问题,用 telnet/ssh 登录了远程的 Linux 服务器,运行了一些耗时较长的任务, 结果却由于网络的不稳定导致任务中途失败。

如何让命令提交后不受本地关闭终端窗口/网络断开连接的干扰呢?下面举了一些例子, 您可以针对不同的场景选择不同的方式来处理这个问题。

nohup/setsid/&

如果只是临时有一个命令需要长时间运行,什么方法能最简便的保证它在后台稳定运行呢?

我们知道,当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。因此,我们的解决办法就有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程。

  1. nohup
    nohup 无疑是我们首先想到的办法。顾名思义,nohup 的用途就是让提交的命令忽略 hangup 信号。让我们先来看一下 nohup 的帮助信息:[code][root@cn example]# man nohup
    NOHUP(1) User Commands NOHUP(1)

NAME
nohup - run a command immune to hangups, with output to a non-tty

SYNOPSIS
nohup COMMAND [ARG]…
nohup OPTION

DESCRIPTION
Run COMMAND, ignoring hangup signals.

   --help display this help and exit

   --version
          output version information and exit

   NOTE:  your  shell  may  have  its own version of nohup, which usually
   supersedes the version described here.  Please refer to  your  shell’s
   documentation for details about the options it supports.

AUTHOR
Written by Jim Meyering.

REPORTING BUGS
Report bugs to [email protected].

COPYRIGHT
Copyright ? 2006 Free Software Foundation, Inc.
This is free software. You may redistribute copies of it under the
terms of the GNU General Public License
http://www.gnu.org/licenses/gpl.html. There is NO WARRANTY, to the
extent permitted by law.

SEE ALSO
The full documentation for nohup is maintained as a Texinfo manual.
If the info and nohup programs are properly installed at your site,
the command

          info nohup

   should give you access to the complete manual.

nohup 5.97 February 2010 NOHUP(1)
(END) [/code]可见,nohup 的使用是十分方便的,只需在要处理的命令前加上 nohup 即可,标准输出和标准错误缺省会被重定向到 nohup.out 文件中。一般我们可在结尾加上"&“来将命令同时放入后台运行,也可用”>filename 2>&1"来更改缺省的重定向文件名。

nohup 示例[root@cn example]# nohup ping www.isharkfly.com nohup: appending output to “nohup.out” [root@cn example]# nohup ping www.isharkfly.com & [2] 31644 nohup: appending output to “nohup.out” [root@cn example]# ps -ef|grep 31644 root 31644 30009 0 08:54 pts/0 00:00:00 ping www.isharkfly.com root 31664 30009 0 08:54 pts/0 00:00:00 grep 31644 [root@cn example]#