Did you forget to start tmux/screen before running a long process? Again?

There are common solutions to be able to run long-running processes in Linux while detaching from the machines. The most commonly used are tmux and screen but I would refer below and describe ‘tmux’ as it is my favorite. Using those tools you are able to save a bash session on the remote host, leaving it still active when disconnecting from the machine. The status of the sessions inside is saved and it is easy to connect to the session later and continue the work instantly, in the same place you stopped earlier. Also, in tmux you are able to have multiple panes in one screen, or even run the same command in multiple places at the same time. Using those tools becomes a habit.

Laptop on a desk
Photo by Joan Gamell on Unsplash

But, I am able to imagine a situation when you start a long-running process that you don’t want to stop when leaving, but meanwhile, you forget to start tmux. It has happened to me countless times. Do you need to stay connected to that session until the process has ended, or you are doomed? Not really. There is a solution using a tool called reptyr.

First things first, you need to temporarily stop the process using the keys combination:

Ctrl + z

Now move it to the background using the command:

bg

And now list jobs in the background using:

jobs -l

There will be printed a process ID in the second column, note it down as it will be required later. I would refer to it using <process_id>.

To be able to attach to that process in a different bash session, you need to disown it from the current session using:

disown <process_id>

Start your tmux session right now, and, if not present yet, install the reptyr. Now, inside tmux pane, run:

reptyr <process_id>

And it is done. If there is an error, check the solutions below.

Troubleshooting

If there is an error saying your process has subprocesses, add -T flag, like:

reptyr -T <process_id>

If it says something with “ptrace” run:

vim /etc/sysctl.d/10-ptrace.conf

And change the variable value kernel.yama.ptrace_scope to 0, rerun reptyr command, and then change it again to the initial value. You don’t want to leave a security flaw.

If there is an error with permissions, just use sudo, like:

sudo reptyr <process_id>

Good luck and see you around.

Sources:

Source: Originally published on Medium on 5 October 2023.