nohup vs tmux: how to keep a Python job running after SSH disconnects

nohup vs tmux: how to keep a Python job running after SSH disconnects

A dropped SSH connection sends SIGHUP to your jobs. We simulated one: a plain background job died, while nohup, disown and tmux kept running. Here is when to use each, and why a clean exit behaves differently.

Use nohup (or disown) for a fire-and-forget Python job with output in a log file. Use tmux when you want to come back later and see the live terminal. All three survived our simulated SSH disconnect; a plain python train.py & was killed when the shell received the hang-up signal (SIGHUP).

Background jobs after a simulated SSH disconnect

SIGHUP (“hang up”) is the signal a shell receives when its terminal goes away. By default, it ends the process. An interactive bash resends SIGHUP to all its jobs before exiting, killing the background job. This signal behavior comes from bash itself and applies the same way on Linux servers; the GNU Bash manual: Signals describes SIGHUP, disown and huponexit (checked 2026-09-28).

The tests ran on 2026-09-28 on macOS with bash 3.2.57, tmux 3.7c and Python 3.12.

We started the same Python script (it prints a line every second) in four ways inside an interactive bash, then closed the terminal underneath it, which is what a dropped SSH connection does:

python3 job.py plain > plain.log 2>&1 &                        # 1. plain background job
nohup python3 job.py nohup > nohup.log 2>&1 &                  # 2. nohup
python3 job.py disown > disown.log 2>&1 & disown               # 3. background job, then disown
tmux new-session -d -s e9 "python3 job.py tmux > tmux.log 2>&1" # 4. inside a detached tmux session

Three seconds after the hangup:

plain   killed
nohup   still running
disown  still running
tmux    still running
MethodSurvives a dropped connectionCan you see live output later?Typical use
command &NoOnly if redirected to a fileShort jobs while you stay logged in
nohup command > log 2>&1 &YesLog file onlyLong batch jobs, training runs
command & disownYesLog file onlyYou started a job and forgot nohup
tmux sessionYesYes, reattach any timeInteractive work, watching progress bars

We ran the test twice with the same result. The plain job’s log stopped at the moment of the hangup; the other three kept writing. The full test harness is at the end of this post.

Clean exit and bash’s huponexit option

A clean logout sends SIGHUP to jobs when bash’s huponexit option is on. With the default setting, it is off. We repeated the experiment and ended the session with exit:

huponexit      	off
plain job after a clean `exit`: still running

The same python train.py & survived a deliberate exit and died when the connection dropped. Wi-Fi loss or a laptop going to sleep can drop the connection. Use nohup, disown or tmux so the job survives both a clean exit and a dropped connection.

How do you use nohup?

nohup makes the command ignore SIGHUP, as described in the nohup(1) man page. disown removes a job from the shell’s job list, so bash skips it when resending the signal.

nohup python3 train.py > train.log 2>&1 &   # start; stdout and stderr go to train.log
tail -f train.log                           # watch the output (Ctrl+C stops watching, not the job)
pgrep -f train.py                           # find the process ID
pkill -f train.py                           # stop it

Always redirect output. Otherwise nohup writes to a file named nohup.out in the current directory. > overwrites the log on each start; use >> to append instead. If you already started a job without nohup, run disown right after it (or disown %1 for job number 1).

pkill -f train.py stops every process whose command line contains train.py, including other people’s runs. To stop only the job you started, save its process ID right away with $!, bash’s special parameter for the last background job (checked 2026-11-02):

nohup python3 -u train.py >> train.log 2>&1 &
echo $! > train.pid
ps -p "$(cat train.pid)" -o pid=,args=   # check that this PID is still your job
kill "$(cat train.pid)"                   # sends SIGTERM, so the job can clean up

A process ID can be reused after the job ends, so look at the ps line before you kill with an old train.pid. kill reaches only that one process; if your script starts child processes, they may keep running.

Start and reattach a tmux session

tmux runs your program under its own server process, independently of your SSH session. The tmux Getting Started guide covers creating, detaching and reattaching sessions:

tmux new -s train          # start a session named "train"
python3 train.py           # run your job as usual
# press Ctrl+b, then d     # detach: the session keeps running
tmux ls                    # later, even from a new SSH login: list sessions
tmux attach -t train       # reattach and see the live terminal
tmux kill-session -t train # remove the session when done

In our test, tmux ls still listed the session after the original terminal was gone:

e9: 1 windows (created Mon Sep 28 18:36:47 2026)

The attach and detach steps above are standard tmux usage. Our automated test used tmux new-session -d; Ctrl+b d is the manual detach sequence.

Job lifetime, error logs and session placement

  • Relying on & alone. The plain background job survived a clean exit and died when the connection dropped.
  • Forgetting 2>&1. Errors then go to the terminal, which no longer exists, and you lose the traceback.
  • Starting tmux on your laptop. tmux must run on the server where the job runs.
  • Killing with ps | grep. grep also matches itself. pgrep -f finds matching processes; pkill -f stops all matches.
The test harness (Python, macOS/Linux)
# job.py
import sys, time
for i in range(60):
    print(f"{sys.argv[1]} step {i}", flush=True)
    time.sleep(1)
# setup.sh
export PATH=/opt/homebrew/bin:$PATH
python3 job.py plain > plain.log 2>&1 & echo $! > plain.pid
nohup python3 job.py nohup > nohup.log 2>&1 & echo $! > nohup.pid
python3 job.py disown > disown.log 2>&1 & echo $! > disown.pid; disown
tmux new-session -d -s e9 "python3 job.py tmux > tmux.log 2>&1"
sleep 1; tmux list-panes -t e9 -F '#{pane_pid}' > tmux.pid
# hangup_test.py: runs setup.sh in an interactive bash on a pseudo-terminal, then closes the terminal
import os, pty, time
W = os.path.dirname(os.path.abspath(__file__))
pid, fd = pty.fork()
if pid == 0:
    os.chdir(W)
    os.execvp("bash", ["bash", "--norc", "--noprofile", "-i"])
time.sleep(1.5)                          # let the shell start
os.write(fd, b"source setup.sh\n")
time.sleep(5)
os.close(fd)                             # the terminal goes away, like a dropped SSH connection
time.sleep(3)
for name in ["plain", "nohup", "disown", "tmux"]:
    p = int(open(f"{W}/{name}.pid").read().strip())
    try:
        os.kill(p, 0); state = "still running"
    except ProcessLookupError:
        state = "killed"
    print(f"{name:<7} {state}")