C.W.K.
Stream
Lesson 05 of 10 · published

Background and nohup

~8 min · nohup, disown, background

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Surviving the terminal close

A normal background job (./script &) dies when its parent shell exits, because the shell sends SIGHUP. Three ways to keep the job alive after you close the terminal:

  • nohup ./script & — start with no-hangup. SIGHUP is ignored. Output goes to nohup.out in the current dir.
  • ./script & disown — start, then detach the most recent job from the shell's job table.
  • setsid ./script & — start in a new session (decoupled from the controlling terminal entirely).

Don't forget the streams

If the script still writes to the original stdout/stderr (a pipe to the terminal), it'll get SIGPIPE when that terminal closes. Always redirect:

nohup ./script > out.log 2>&1 &

The right tool for long-running stuff

For things you'll come back to: tmux new -s build './script.sh' + tmux attach -t build later. The session keeps a pseudo-terminal alive even when nobody's looking.

For real services: macOS launchd or Linux systemd unit files. The Pippa stack uses launchd to keep pippa serve alive.

Check if a backgrounded job is alive

kill -0 PID && echo alive
ps -p PID

kill -0 sends signal 0, which is "check if you can" rather than "actually do it." Returns 0 if the process exists.

Code

Reliable detached run·bash
nohup ./long-job.sh > job.log 2>&1 &
echo $!         # save the PID
disown          # remove from this shell's table
# now exit the terminal — job lives on

External links

Exercise

Start a fake long task: nohup sh -c 'for i in $(seq 1 30); do echo tick $i; sleep 1; done' > /tmp/tick.log 2>&1 &. Get its PID with $!. Close the terminal. Open a new one. cat /tmp/tick.log — see it kept ticking.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.