How to Detach a Running Process from Terminal: Alternative to Nohup/Screen


2 views

When you SSH into a Linux server and launch a long-running process without using screen, tmux, or nohup, that process becomes tied to your terminal session. If the connection drops or you close the terminal, the process typically receives a SIGHUP signal and terminates.

The reptyr tool allows moving running processes between terminals:


# Install reptyr on Debian/Ubuntu
sudo apt-get install reptyr

# Find the PID of your running process
ps aux | grep your_process

# Attach to screen/tmux first, then:
reptyr PID

Bash's built-in disown command can help:


# Start process normally
./long_running_script.sh &

# List jobs
jobs -l

# Disown the job (replace %1 with your job number)
disown -h %1

# Now the process won't receive SIGHUP
exit

For critical processes where other methods fail:


# Install gdb if not available
sudo apt-get install gdb

# Attach to process
gdb -p PID

# In gdb prompt:
(gdb) call setpgid(0,0)
(gdb) detach
(gdb) quit

For future sessions, consider:


# Always use screen/tmux for long jobs
tmux new -s longjob
./your_script.sh
# Ctrl+b then d to detach

# Or use nohup properly
nohup ./script.sh > output.log 2>&1 &
  • Some processes may still terminate due to other dependencies on the terminal
  • Systemd services provide better process management for production environments
  • Check process hierarchy with pstree -p PID before attempting detachment

We've all been there - you SSH into a server, start a long-running process, and suddenly realize you should have used screen or nohup from the beginning. The process is tied to your terminal session, and closing SSH will kill it.

reptyr is a powerful tool that can "steal" a running process and attach it to a new terminal:


# Install reptyr (Debian/Ubuntu)
sudo apt-get install reptyr

# Find your process ID
ps aux | grep your_process

# Start a screen session
screen

# In the screen session, attach the process
reptyr PID

For processes that resist reptyr, gdb can help:


# Attach gdb to the process
gdb -p PID

# In gdb prompt:
(gdb) call close(0)
(gdb) call close(1)
(gdb) call close(2)
(gdb) call open("/dev/null", 0)
(gdb) call dup(0)
(gdb) call dup(0)
(gdb) detach
(gdb) quit

If you can't install new tools, try this sequence:


# Disown the process (bash specific)
disown -h %1

# Optional: redirect output if needed
exec >/dev/null 2>&1

To avoid this situation in the future:

  • Always use screen or tmux for long-running processes
  • Consider nohup command & as a simple alternative
  • For critical processes, use proper init systems like systemd

Imagine you started a MySQL dump without screen:


# Original command that's running
mysqldump -u root -p database > backup.sql

# In another terminal:
screen
reptyr $(pgrep -f "mysqldump")
# Ctrl+A then D to detach