How bash handles the jobs when logout?

Unni picture Unni · Nov 28, 2010 · Viewed 9.3k times · Source

As far as I understood from the books and bash manuals is that. When a user logs out from bash all the background jobs that is started by the user will automatically terminate, if he is not using nohup or disown. But today I tested it :

  1. Logged in to my gnome desktop and accessed gnome-terminal.
  2. There are two tabs in the terminal and in one I created a new user called test and logged in as test

    su - test
    
  3. started a script.

    cat test.sh
    #!/bin/bash
    sleep 60
    printf "hello world!!"
    exit 0
    
    
    ./test.sh &
    
  4. After that I logged out of test and closed the tab

  5. In the next tab I exected ps aux as root and found that job is still running.

How this is happening ?

Answer

jilles picture jilles · Dec 1, 2010

Whether running background jobs are terminated on exit depends on the shell. Bash normally does not do this, but can be configured to for login shells (shopt -s huponexit). In any case, access to the tty is impossible after the controlling process (such as a login shell) has terminated.

Situations that do always cause SIGHUP include:

  • Anything in foreground when the tty is closed down.
  • Any background job that includes stopped processes when their shell terminates (SIGCONT and SIGHUP). Shells typically warn you before letting this happen.

huponexit summary:

  • On: Background jobs will be terminated with SIGHUP when shell exits

    $ shopt -s huponexit
    $ shopt huponexit
    huponexit       on
    
  • Off: Background jobs will NOT be terminated with SIGHUP when shell exits.

    $ shopt -u huponexit
    $ shopt huponexit
    huponexit       off