Background:
- Connect to Ubuntu server via ssh
- Run tmux and detach
Why the PPID of tmux is 1? Any information on tmux runtime mechanism?
Answer
tmux
runs in a client-server architecture. Whenever you run tmux
from a shell, you run a client that is a child of the shell. (It's possible to run tmux
from not-a-shell, e.g. directly from sshd
, this detail changes nothing).
tmux
client tries to find a tmux
server associated to your user. If no server can be found, sometimes the client will complain (e.g. tmux attach-session
) and sometimes it will start a server (e.g. sole tmux
, which is equivalent to tmux new-session
) and then do its job.
The job of any tmux
client is to talk to the server and make the server do something.
When tmux
needs to start a server, it does clone(2)
itself. The resulting child process immediately clone
s again and then exits. The newest process becomes the actual tmux
server and its PPID is 1 because its parent has died. It looks like the only job of the intermediate process is to "detach" the server from its ancestors.
I think it might work with tmux
server being the immediate child of some tmux
client, then gaining PPID of 1 only after the client dies. Note the whole point of tmux
is to have a server that keeps running after the original client is detached; so if the server was a child of some client, it would most likely be orphaned sooner or later anyway. And because in general tmux
client can be run from any shell or another process, which may try to monitor its children's children, send signals to them etc., orphaning the server as soon as possible is a reasonable thing to do.
So the server gets PPID of 1 almost immediately. Every shell or another process you run within tmux
is a descendant of the server. After you (re-)attach, you see what the client shows you. The client itself is a child of the shell you invoked it in (or sshd
or whatever). It talks to the server, passes keystrokes to it, receives information on how the window should look like and prints characters accordingly.
The server, once started, runs until all sessions within are killed. This means in order to gracefully terminate it, you need to terminate all shells (or other processes) being panes.
This architecture explains why the environment of the firstly invoked tmux
can be preserved but in general the environment of tmux
clients may not matter. The server starts as a grandchild of the first tmux
, so it can inherit the environment. After this everything depends on the server. As long as the server runs, there's no direct inheritance from any later client because neither the server nor newly spawned processes (panes) are descendants of this client. See this answer of mine.
No comments:
Post a Comment