Why nohup background process is getting killed

background-processnohup

I tried starting a shell script via a remote session, which starts a process in the background using the command.

nohup python3 run.py > nohup.out &

When the remote session is closed, the process is getting killed with the message:

Caught signal SIGHUP

SIGHUP caught but not daemonized. Exiting.

I don't understand; why is the process getting killed when it was started in background using nohup &?

Best Answer

Your Python program undoes nohup.

nohup ignores the hangup signal with SIG_IGN and then chain loads your program in the same process.

Your Python program promptly resets the signal handling for the hangup signal, installing its own signal handler. That handler checks an internal function (that is not designed very well, being based upon some flawed assumptions, if it is the one that I have seen) and decides that the appropriate course of action on receipt of a hangup signal is to print that message and exit.

Your Python program by design is not nohup-able. On a system with a job control shell and POSIX session/job semantics, you need to be disowning the job so that the shell never knows about it to send a hangup signal to it in the first place.

(Even that is not enough on systemd operating systems. Because the systemd people have made a bit of a pig's ear of their user-space login session mechanism, you also need to ensure that systemd's mechanism that signals system shutdown, rather than hangup, to login sessions at every logout is also not kicking in.)

Further reading

Related Question