判断SSH退出后子进程是否会被关闭有以下几种情况:

  1. 如果打开了huponexit,所有的子进程在SSH退出后全都会接到SIGHUP信号,除非程序自己处理SIGHUP信号并且不退出,否则程序退出
    • huponexit打开时,可以使用nohup或者disown使进程不退出.原理是nohup捕获了SIGHUP信号,disown是告诉SHELL不给程序发送SIGHUP信号
    • huponexit没有打开时,如果SSH正常logout,后台子进程不会自己退出
    • huponexit没有打开时,如果SSH非正常退出(比如断网,强行关闭SSH软件),所有子进程都会被kill
    • 正确的使用screen也可以防止子进程在SSH断开时退出

查看huponexit是否打开的方法

shopt | grep huponexit

&是干什么用的?

man bash可以看到如下描述

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

为什么nohup有时要和&一起使用?

man nohup可以看到下面这句

‘nohup’ does not automatically put the command it runs in the background; you must do that explicitly, by ending the command line with an `&’.

参考

  1. Bash & (Ampersand)
  2. What’s the difference between nohup and ampersand
  3. How bash handles the jobs when logout?
  4. What exactly determines if a backgrounded job is killed when the shell is exited, or killed?
本文地址 如何保证SSH退出后子进程不关闭 转载请注明出处