http://www.cooklife.cn/detail/54a66aea268aeafe034003b3#View
今天碰到这么一个问题,使用ssh客户端登陆了linux服务器,启动并运行服务之后如果关闭客户端与服务器的连接,这个时候运行于服务器上的服务也会被关闭,如何让命令提交之后不受本地关闭终端端口的影响呢?
首先我们要知道为啥客户端的断开会影响服务端程序的运行?
当用户注销或者网络断开时,终端会受到hangup信号从而关闭其所有的子进程,因此我们要解决的办法有两种途径
- 忽略hup信号。nohup命令
- 者让进程运行在新的会话里从而成为不属于此终端的子进程。setsid命令
nohup
nohup可以让运行的线程忽略掉hangup信号,我们看看nohup的帮组信息
NAME nohup - run a command immune to hangups, with output to a non-tty SYNOPSIS nohup COMMAND [ARG]... nohup OPTION
nohup的语法很简单,只需要在执行的命令之前加上nohup即可。
setsid
如果我们让运行的线程不属于接受hangup信号终端的子线程,那么该运行线程也不会受终端关闭的影响。通过setsid命令在另外一个session中启动服务,看看setsid的帮组信息:
NAME setsid - run a program in a new session SYNOPSIS setsid program [arg...] DESCRIPTION setsid runs a program in a new session.
可以看到setsid命令的使用方法同nohup命令同样简单,在运行的命令之前加上setsid命令。
有的时候,我们可能忘记了加上命令nohup或者setsid命令,但是在退出终端的时候却需要服务在后台运行,有挽救的方法么? 答案是有的,通过disown命令可以让启动的服务在后台稳定的运行,我们先看看disown的帮助信息:
disown [-ar] [-h] [jobspec ...] Without options, each jobspec is removed from the table of active jobs. If jobspec is not present, and neither -a nor -r is supplied, the shell鈥檚 notion of the current job is used. If the -h option is given, each jobspec is not removed from the ta- ble, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a job- spec does not specify a valid job.
-h jobspec:让某个job忽略掉 hup信号 -ah:让所有的job忽略掉hup信息 -rh:让正在运行的job忽略掉hup信息