It happened. Admit it 🙂
You started a task on a server and now it’s 5 to 5pm (16:55 in military talk) and the task is only about half way through. And the little voice in your head goes: “Why, oh, why haven’t I started it in a screen instance?”
Well, settle in and keep reading, you weren’t going home till the task was finished anyway.
Let’s take wget as an example. Probably not the most fitting example but it will serve nicely. Here it is, chugging along with a steady pace of 500kb/s:
[me@localhost ~]# wget --limit-rate=500k http://www.example.com/files/a_large_file.file --2019-05-14 16:21:26-- http://www.example.com/files/a_large_file.file Resolving www.example.com (www.example.com)... 172.16.10.1 Connecting to www.example.com (www.example.com)|172.16.10.1|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 2097152000 (2.0G) [application/octet-stream] Saving to: ‘a_large_file.file’ 50% [=====================> ] 1,069,145,045 500KB/s eta 33m 34s
First, I suspect you already know about screen. Next install reptyr from your preferred installation source. I mostly deal with RHEL base systems, so:
[me@localhost ~]# yum install reptyr
Start a screen session, this is my preferred way:
[me@localhost ~]# screen -S process_move bash
Find the PID of the process you want to attach to your screen session:
[me@localhost ~]# ps -a PID TTY TIME CMD 4934 pts/2 00:00:00 wget <-- this it the one we want 4975 pts/0 00:00:00 screen 4977 pts/3 00:00:00 ps
Finally run reptyr with the PID as the input and the process will be transplanted to your screen session:
[me@localhost ~]# reptyr 4934 51% [======================> ] 1,071,602,645 500KB/s eta 33m 30s
Close the screen session with »CTRL+a d«:
[me@localhost ~]# screen -S process_move bash [detached from 4455.process_move]
Check the time:
[me@localhost ~]# date Tue May 14 17:00:01 CEST 2019
Darn… Look at how late it is already. The pesky culprit that kept you at work waaaaaaay past your office hours was succesfully transplanted into a screen session and now you can finally leave. Lesson learned! …until the next time you forget to run stuff in screen…😂
Caveat
And now for bit of a cold shower if you are using CentOS 7 like me. By installing reptyr from the official RPM repo you get version 0.5. With that version you cannot transplant bash scripts, it only works for single processes.
There is however a newer version available here on GitHub. It provides a new feature called TTY stealing and it enables you to transplant bash scripts as well. You can read more about it in the author’s post.