medium.com 6 min read Original Source

The One Linux Command That Moves a Running Process Into a New Terminal

You connect to a server over SSH. You start a job that will take two hours. A backup. A big compile. A database migration.

Twenty minutes in you realise your laptop battery is almost dead. Or your train is about to enter a tunnel. Or your Wi Fi has started to flicker. You remember what happens when an SSH session drops. The job dies with it. Twenty minutes of work gone.

You also remember what you should have done. You should have started it inside tmux. Too late now. You cannot stop the job without losing it.

Or can you? Linux has a small tool that takes a program that is already running and hands it to a different terminal. You start tmux now. You move the job into it. Then you can close your laptop. The tool is called reptyr.

Why Closing a Terminal Kills Your Job

Programs you start from a shell are tied to the terminal window or SSH session they came from. That terminal is called their controlling terminal. When the terminal closes the system sends a signal to everything attached to it. The signal is called SIGHUP. The name comes from hang up, because it dates from the days of telephone modems. Many programs respond to it by quitting.

This is why a dropped SSH connection kills your job. The session ends. The terminal vanishes. The kernel sends the hang up signal. Your program stops.

A tool such as tmux avoids the problem. It runs on the server in its own terminal that does not depend on your connection. Your SSH session becomes just a window looking into it. If the window closes tmux and everything inside it keeps running. You can reconnect later and look again.

The problem arrives when you forgot to use it.

The Quick Fixes and Their Limits

You may have heard of two other tools for this situation.

The nohup command starts a program so that it ignores the hang up signal. It must be used at the start. You cannot apply it to something already running.

The disown command removes a job from the shell’s list. After that the shell does not send the hang up signal to it when you leave. This works on a running job. It has a cost. The program still points its input and output at the old terminal. When that terminal goes away the program may crash the next time it writes a message. You also lose the ability to type into it or watch its output.

So disown can save the process at the cost of control. If the job needs no input and you do not care about its output that may be enough. If you want to see progress or answer a question you need more.

What reptyr Does

The name means re parent to a new pseudo terminal. The reptyr tool takes a running process and attaches it to your current terminal. The program now believes it started here. Its output appears on your screen. Your keystrokes reach it.

It uses a debugging feature of the kernel called ptrace. That feature lets one program inspect and control another. The tool briefly takes control of the target. It swaps the terminal connections inside it. Then it lets go and the program carries on as if nothing happened.

The result is that you can start tmux now and pull the job into it. The job gains the safety you wished it had from the start.

Install the Tools

You need reptyr and tmux.

sudo apt install reptyr tmux
sudo apt install reptyr tmux

On Fedora use sudo dnf install reptyr tmux. On the server you are working on both need to be installed. Ideally install them before you need them. Doing it mid crisis is possible if you have network access and permission.

Try It Safely With a Counter

Practise on something harmless. Create a script that counts forever. Save this as counter.sh.

#!/bin/bash
for i in $(seq 1 600); do
  echo "tick $i"
  sleep 1
done
#!/bin/bash
for i in $(seq 1 600); do
  echo "tick $i"
  sleep 1
done

The script prints a line every second for ten minutes. Start it in a terminal.

bash counter.sh
tick 1
tick 2
tick 3
bash counter.sh
tick 1
tick 2
tick 3

You will move this running job into another terminal. Leave it going.

The Steps to Rescue a Job

Follow this order.

Step one is to pause the job

Press Ctrl+Z in the terminal where the job runs.

^Z
[1]+  Stopped                 bash counter.sh
^Z
[1]+  Stopped                 bash counter.sh

The line shows the job is now stopped. It has job number 1. Ctrl+Z asks the shell to suspend the foreground program. The program is frozen and not running.

Step two is to resume it in the background

bg
[1]+ bash counter.sh &
bg
[1]+ bash counter.sh &

The bg command restarts the stopped job and lets it run in the background. The ticks start appearing again. They still print to your screen. The prompt is yours again.

Step three is to find its process ID

Every process has a number. You need that number for reptyr. The jobs command shows it with the -l flag.

jobs -l
[1]+  4821 Running                 bash counter.sh &
jobs -l
[1]+  4821 Running                 bash counter.sh &

The number after the job number is the process ID. Here it is 4821. Yours will differ. You can also find it by name from any terminal.

pgrep -af counter.sh
4821 bash counter.sh
pgrep -af counter.sh
4821 bash counter.sh

The -a flag shows the full command. The -f flag matches against the whole command line. This is useful when the program name is a script.

Step four is to detach it from the old shell

disown %1
disown %1

The %1 refers to job number 1. The command prints nothing. The shell now forgets this job. When the old terminal ends the shell will not send it the hang up signal. This protects the program for the short moment before you move it.

Step five is to start tmux

Open the new terminal where you want the job to live. On the server start a tmux session.

tmux new -s rescue
tmux new -s rescue

The -s rescue part gives the session a name. You land in a fresh terminal inside tmux.

Step six is to attach the process

Inside tmux run reptyr with the process ID.

reptyr 4821
tick 85
tick 86
tick 87
reptyr 4821
tick 85
tick 86
tick 87

The ticks now appear inside tmux. The job moved. Press Ctrl+C here and it stops. That proves your keystrokes reach it. You are in full control again.

Step seven is to detach and leave

Press Ctrl+B and then the letter D. This detaches tmux. The job keeps running in it. Close your SSH session if you need to. Later reconnect and bring everything back.

tmux attach -t rescue
tmux attach -t rescue

You see the job exactly where it is now. The ticks have kept counting while you were away.

Confirm the Move

You can check that the job really changed terminals. The ps command shows the terminal each process is attached to.

ps -o pid,tty,cmd -p 4821
ps -o pid,tty,cmd -p 4821

Before the move it looks like this.

PID TT       CMD
   4821 pts/0    bash counter.sh
PID TT       CMD
   4821 pts/0    bash counter.sh

After running reptyr inside tmux it shows a different terminal.

PID TT       CMD
   4821 pts/3    bash counter.sh
PID TT       CMD
   4821 pts/3    bash counter.sh

The -o flag chooses the columns. The -p flag picks the process. The TT column is the terminal. It changed from pts/0 to pts/3. Your process lives in the tmux terminal now. Closing the old SSH session will not touch it.

When Permission Is Denied

You may see an error like this instead of success.

Unable to attach to pid 4821: Operation not permitted
The kernel denied permission while attaching. If your uid matches the target's, check the value of /proc/sys/kernel/yama/ptrace_scope.  For more information, see /etc/sysctl.d/10-ptrace.conf
Unable to attach to pid 4821: Operation not permitted
The kernel denied permission while attaching. If your uid matches the target's, check the value of /proc/sys/kernel/yama/ptrace_scope.  For more information, see /etc/sysctl.d/10-ptrace.conf

Many distributions such as Ubuntu protect against one process spying on another. A kernel module called Yama limits the debugging feature that reptyr needs. At its default setting a normal user can only trace their own child processes. Your job is not a child of the new terminal. So the kernel says no.

Check the current value.

cat /proc/sys/kernel/yama/ptrace_scope
1
cat /proc/sys/kernel/yama/ptrace_scope
1

A value of 1 is the restrictive default.

The simplest fix is to run the tool as root. Root has the right to trace any process.

sudo reptyr 4821
sudo reptyr 4821

If that is not possible you can relax the setting for a short time.

echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

The change lasts until the next reboot. Move your job. Then restore the safe value straight away.

echo 1 | sudo tee /proc/sys/kernel/yama/ptrace_scope
echo 1 | sudo tee /proc/sys/kernel/yama/ptrace_scope

Do not leave it at 0. That setting lets any program running as you inspect and tamper with your other programs. It is a real security downgrade. Treat it as an emergency measure and not a permanent choice.

What reptyr Cannot Do

The tool is clever and it has limits.

It works best on a single program. A job that starts many child programs such as a build that launches dozens of compilers may not move cleanly. Test on something simple first if you can.

Full screen programs such as editors may need a redraw. Press Ctrl+L or resize your terminal window to make them repaint.

It cannot move a process into a terminal on a different machine. Both terminals must be on the same system.

Processes inside some containers cannot be reached because they live in a separate view of the system.

A tool that tampers with another process can go wrong. Do not use it on a job whose loss would be a disaster unless you have a backup. For anything critical start the job inside tmux from the beginning.

Habits That Prevent the Problem

The best rescue is the one you never need.

Start tmux first whenever you connect to a server for long work. Make it the first command you type after login.

tmux new -s work
tmux new -s work

Name your sessions. Reconnect with tmux attach -t work.

Use nohup or setsid when you launch a single background job that needs no input. Redirect its output to a file so you can read it later.

backup.log 2>&1 &” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

nohup ./backup.sh > backup.log 2>&1 &
nohup ./backup.sh > backup.log 2>&1 &

The > backup.log 2>&1 part saves normal and error output into one file. The final ampersand puts it in the background. You can watch progress with tail -f backup.log.

Keep reptyr installed on your servers. It costs almost nothing to have and it saves a job once in a while.

I wanted to create a place where learning the terminal involves more than memorising commands and following instructions. The goal is to help learners become more comfortable investigating problems and figuring things out for themselves.

If you’re learning Linux and want to experience a more hands-on approach, you can explore it here: Terminal Academy.