Search code examples
bashshellsshrootdetach

shell - Process detached by running in background and redirecting STDIN/OUT?


In an ssh session on a server I started some bash processes (that start other processes) in the background with & and redirected their stdin / stdout to file (<dev/null >mylog.out).

The processes are not listed under jobs and ps -T shows only one bash process and ps itself.

Most of the (child) processes are run by user root but are all linked to a specific TTY pts/20.

If I close the ssh session, will the processes and their children be sent the HUP signal or will they continue running? If yes, how could I completely detach them?


Solution

  • If you put a process in the background the process will ignore the SIGHUP command. So the process will continue to run.

    Test results:

    Login and run bash script o.sh in background and exit:

    system:10.11.2.122 > o.sh &
    system:10.11.2.122 > exit 
    

    Login back into system and check o.sh process:

    system:10.11.2.122 > ps -ef | grep o.sh
    root     19115     1  0 10:10 ?        00:00:00 /usr/local/bin/bash /root/scripts/o.sh
    root     27774 20197  0 10:23 pts/2    00:00:00 grep o.sh
    

    This method daemonises a running process.

    With bash, this behavior is dependent on the huponexit shell option. These, and other option settings, can be seen using the shopt command on CentOS/RedHat 6.7.

    huponexit appears to be off by default on CentOS/RedHat 6.7.

    A subset of the output of shopt:

    histappend      off
    histreedit      off
    histverify      off
    hostcomplete    on
    huponexit       off
    interactive_comments    on
    lithist         off
    login_shell     on
    mailwarn        off
    no_empty_cmd_completion off
    nocaseglob      off
    nocasematch     off
    nullglob        off
    

    So to answer your questions:

    If I close the ssh session, will the processes and their children be sent the HUP signal or will they continue running?

    That depends on your huponexit setting. If huponexit is off, then no and process will continue to run. Otherwise, yes.

    If yes, how could I completely detach them?

    Use the nohup command when executing the process.

    nohup your_process &