Moving a Running Process to screen

I am not sure how many times this has happened to me, but it’s not infrequent. I’m working on a remote session and I start a long running job. Then some time later I want to disconnect from the session but realise that if I do then the job will be killed.

I should have started job in screen or tmux!

So, is it possible to transfer the running process to screen? (Or, equally, to tmux?) Well it turns out that it is using the reptyr utility. I discovered this thanks to a LinkedIn post by Bruce Werdschinski. A slightly refinement of his process is documented below.

Create a Long Running Job

For illustration purposes, let’s kick off a long running job.

$ tail -f /var/log/syslog

That should start logging text to the terminal.

Find the Process ID

Now we need to find out the PID for that process.

  1. Suspend the process using Ctrl-z.
[1]+  Stopped                 tail -f /var/log/syslog
  1. Find the PID using jobs.
$ jobs -l
[1]+ 20562 Stopped                 tail -f /var/log/syslog

Right, so the PID is 20562.

Transfer Process to screen

At this point we need to get around a small wrinkle, circumventing a minor security measure.

  1. Enable ptrace.
$ echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
  1. Start a screen session.
$ screen
  1. Use reptyr to reparent the process.
$ reptyr 20562

The suspended process will be resumed.

  1. Disconnect from the screen session.
  2. Disable ptrace.
$ echo 1 | sudo tee /proc/sys/kernel/yama/ptrace_scope

Done!

You can update the ptrace settings permanently, but given that reparenting should not be a frequent process, this is probably not necessary.

Categorically Variable