This works, most of the time:
Prerequisites: have and reptyr/tmux installed; you'll be able to find them with screen or apt-get, depending on your platform.yum
Use Ctrl+Z to suspend the process.
Resume the process in the background with bg
Find the process ID of the background process with jobs -l
You'll see something similar to this:
[1]+ 11475 Stopped (signal) yourprocessname
Disown the job from the current parent (shell) with disown yourprocessname
Start (preferred), or tmux.screen
Reattach the process to the /tmux session with reptyr:screen
reptyr 11475
Now you can detach the multiplexer (default Ctrl+B, D for , or Ctrl+A, D for tmux), and disconnect SSH while your process continues in screen/tmux.screen
Later when you connect with SSH again, you can then attach to your multiplexer (e.g. ).tmux attach
You can revoke “ownership” of the program from the shell with the built-in:disown
# press Ctrl+Z to suspend the program
bg
disown
However this only tells the shell not to send a signal to the program when the shell exits. The program will retain any connection it has with the terminal, usually as standard input, output and error streams. There is no way to reattach those to another terminal. (Screen works by emulating a terminal for each window, so the programs are attached to the screen window.)SIGHUP
It is possible to reattach the filedescriptors to a different file by attaching the program in a debugger (i.e. using ) and making it call ptrace, open and dup. There are a few tools that do this; this is a tricky process, and sometimes they will crash the process instead. The possibilities include (links collected from answers to How can I disown a running process and associate it to a new screen shell? and Can I nohup/screen an already-started process?):close
You can not re-attach a process id. You need to reattach the corresponding session.tmux
So do . Pick whatever session you want to re-attach. Then do tmux ls to re-attach it to a new tmux instance and release it from the old one.tmux attach -d -t <session id>
There is no portable way to do this. There is a program https://github.com/nelhage/reptyr that can do this on Linux (it uses ptrace and interposes all the system calls), but I don't know how reliable it is or if it is still maintained. YMMV.
You can list tmux sessions when reconnecting to the remote server:
tmux ls
0: 4 windows (created Tue Oct 15 07:55:07 2019) [255x62]
1: 2 windows (created Tue Oct 15 07:55:07 2019) [255x62]
You can then reattach to a target session:
tmux attach-session -t 1
This would attach to the second tmux instance listed above.
If you just have one tmux session running, then you can use the shorthand:
tmux a
to reattach the first session.