LINUX-PRODUCTION Contents

Background Jobs (nohup, tmux, systemd-run)

Run long tasks reliably without losing sessions or leaving orphaned processes.

On this page

Why Background Execution Is Dangerous in Production

Running something in the background is easy. Running it safely in production is not. Improper background execution can result in:

  • Half-completed migrations
  • Lost logs
  • Orphaned processes
  • Jobs silently dying after SSH disconnect

In production, background execution must be intentional.

The SSH Problem

When you close an SSH session, the shell sends SIGHUP to child processes. If your job does not handle it, it may terminate.

Basic Background Operator (&)

./script.sh &

This runs in background but still tied to the shell. Closing SSH can kill it. Not production-safe by default.

nohup: Survive SIGHUP

nohup prevents the process from receiving SIGHUP.

nohup ./script.sh > output.log 2>&1 &

Important:

  • Always redirect output explicitly
  • Monitor logs
  • Confirm process is still running

Check Background Job Status

jobs
ps aux | grep script.sh

Do not assume it is running — verify.

Better Tool: tmux

tmux creates a persistent terminal session independent of SSH.

tmux new -s maintenance

Detach:

Ctrl+B then D

Reattach later:

tmux attach -t maintenance

tmux is safer than nohup for interactive or long-running maintenance tasks.

Best Practice for Production: systemd-run

Instead of manual background jobs, prefer systemd supervision.

systemd-run --unit=manual-job --scope ./script.sh

Advantages:

  • Proper logging in journal
  • Controlled lifecycle
  • Resource tracking
  • Better auditability

Orphaned Processes

If a parent shell dies, background processes may become orphaned and adopted by PID 1. This can make debugging harder because:

  • No clear owner
  • No supervision
  • No structured logs

When NOT to Use Background Jobs

  • Database migrations
  • Production schema changes
  • Critical deploy steps
  • Anything without clear monitoring

If the job matters, supervise it.

How to Verify a Job Is Still Running

ps -ef --forest | grep script
journalctl -u manual-job

Common Production Mistakes

  • Running migrations with & and disconnecting
  • Forgetting output redirection
  • Using screen/tmux but never checking logs
  • Leaving orphaned heavy jobs consuming CPU

Mental Model

Background execution without supervision is risk. Production jobs should be:

  • Observable
  • Supervised
  • Logged
  • Recoverable

Production Checklist

  • Prefer systemd-run or proper service units
  • If using nohup, redirect logs explicitly
  • Use tmux for interactive maintenance
  • Always verify process survival after SSH exit
  • Avoid unsupervised background critical tasks