There are multiple ways to run programs in background in Linux. This can required for various purposes.

But in this article we are going to Cover 2:

  • Using & (ampersand)
  • Using nohup (no hang up) with ampersand

1. & (Ampersand)

The & is a shell operator that allows you to run a command in the background, meaning the shell will not wait for the command to finish. Once the command starts, you can continue using the terminal without blocking.

  • How it works: The command runs as a background process, but it’s still attached to the current shell session. This means:
    • If you close the terminal or log out, the background process will receive the SIGHUP (hangup) signal, which usually terminates the process unless it is programmed to handle this signal.
    • It’s useful when you want to continue working in the same shell session but run a task in the background.

Example:

python3 my_script.py &

This runs the script in the background, but if you close the terminal, the process will typically terminate.

2. nohup (No Hangup)

nohup prevents the process from being terminated if the shell session is closed. It ignores the SIGHUP signal, which is typically sent when you log out or close the terminal.

  • How it works: nohup ensures that the process continues running independently of the terminal session. By default, it redirects the output (both stdout and stderr) to a file called nohup.out unless otherwise specified.
    • Even if you close the terminal or log out, the process will continue running in the background.
    • It’s useful when you want to start long-running processes or tasks that should keep running even after you disconnect from the system.

Example:

nohup python3 my_script.py &

This runs the script in the background, and the script will keep running even if the terminal is closed.

Key Differences:

  • Behavior upon terminal closure:
    • &: The background process will usually terminate when you close the terminal (unless it handles SIGHUP itself).
    • nohup: The process will continue running even after you close the terminal.
  • Output handling:
    • &: The process output will still be tied to the terminal, unless redirected explicitly.
    • nohup: By default, it writes output to nohup.out, unless you redirect it.

When to Use:

  • Use & when you want to run something in the background but are okay with it stopping when the terminal is closed.
  • Use nohup when you want the process to keep running after you log out or close the terminal.

Both can be used together, as in:

nohup python3 my_script.py > output.log 2>&1 &

This ensures the process runs in the background, isn’t killed when you log out, and logs all output to output.log.