Reattaching shell sessions
Ever started a shell session running a process, quickly realizing that will take longer than you expected to finish? For instance, a remote ssh session where you do not want to leave your computer turned on just to keep the session open. Fortunately, there is a workaround by using a combination of screen and reptyr.
For example, imagine that we are running this hypothetic slow process that prints in each second the next number of the Fibonacci sequence:
1 | #!/usr/bin/env python |
1 | $ python fibo.py |
We are now interested in moving this job to another session where we can attach and detach any time, while leaving the job running. In order to achieve this, we start by creating a new screen session in a new window: 1
$ screen -S fibonacci
The screen tool lets us create multiple windows with shells inside. We can also leave those windows at anytime and reenter them later, always leaving their internal programs running. Once we have this new screen session, we can move our running job to this new shell:
1 | $ ps -u | grep fibo.py |
We temporarily enable the ability to attach programs, as root. Then, we grab the process id and pass it to the reptyr tool, which does a great job in moving our old process back to this new shell. We can now detach from this screen session by typing Ctrl + Shift + D and confirming the session is saved:
1 | $ screen -ls |
Later, when can reattach to the screen:
1 | $ screen -r fibo |
PS: You might need to run bash echo 0 > /proc/sys/kernel/yama/ptrace_scope
This is a very simple example with a trivial job running just to illustrate the idea of moving random jobs to new screen sessions. We can avoid this by always starting long running process in new screen sessions. In case we forget, we can use this process to rescue us.