In this lesson, you will learn how to move a process that is already running in one terminal session into another without terminating it.
The Challenge of Terminal Sessions
Normally, when you start a command in a terminal, it is tied to that specific "session." If you close the terminal, the process receives a termination signal and dies. However, using process checkpointing techniques—specifically via the tool reptyr—we can "re-attach" a process from one shell to another. This is incredibly useful if you started a long-running job in one window and realize later you want to manage it from a different terminal or a persistent session like tmux.
How Migration Works
The core idea is to "hijack" the file descriptors (the connection to the terminal) of a running process.
- Pause the process: You first send a
STOPsignal to the process so its state remains consistent. - Snapshot the environment: The system captures the process's current file handles (where it sends its text output and where it gets input).
- Re-attach: By using a debugger-like mechanism (the
ptracesystem call), the new shell "steals" the process, redirecting its input and output to the new terminal window.
Here is the basic workflow:
# 1. In your current terminal, find the process ID (PID)
ps aux | grep my_long_task
# 2. In the target terminal where you want the process to live:
reptyr <PID>
Once reptyr attaches to the process, you can press Ctrl+C or send signals from the new terminal as if you had started the process there originally. The process resumes execution, but now its "home" is your new terminal session.
Important Considerations
Because this technique involves injecting code into a running process, it requires sufficient permissions (usually root or a configured ptrace_scope setting). Additionally, not every process can be migrated; processes that are deeply integrated with specific hardware devices or those that have complex signal handling might become unstable. Always ensure your data is saved before attempting to migrate a critical task.
Key Takeaway: Process migration allows you to detach a running task from one shell and re-attach it to another, ensuring your work continues even if your original terminal session needs to be closed.