The question presupposes you have a single server process but in fact you would need two.
One process is your 'backgrounded' application using the slave end of the pty.
The other process would be a helper which manages the master end of the pty.
The master end must remain opened at all times. The pty pair is removed when the masters file descriptor is closed.
The backgrounded applicaiton on the slave side, reads and writes to its end.
The master side decides what to do with those reads and writes.
To connect from another terminal you need to tell the master end where to send the read and writes.
You could give it the name of the pty terminal you are using somehow. The process managing the master end could then forward the reads and writes as appropriate.
This alone is insufficient for some applications. In particular if the terminal's size is changed the application should recieve a SIGWINCH
. The master will need to pass this to the slave somehow. The terminal capabilities could also differ and require translation.
To handle those your client side needs a third process which talks to the process running the master end of the pty. This is how screen
and tmux
work.
So there is no standard program that does what you want because there is no standard way to handle this. Programs like screen do this their own way but can be used as is in most cases.
In an answer to the linked question the OP (of that question) uses a terminal in raw mode which probably means those complications do not apply.
For example if you just want to forward stdout from the master a pty name to duplicate the output to would be sufficient.
The screen
program on the other hand creates a socket for each virtual screen (running on the master side of the pty). The same screen
executable running (in a different mode) as a client process connects to that socket to talk to the application.
Given that screen and tmux are designed explicitly to do this it is not clear what advantage you would gain from doing this yourself.
It could be an interesting learning exercise however.
The new question describes your use case better.
You could not create new user interfaces on demand with screen.
It does handle the foreground and background use case very nicely so long as you remember to run the process under screen from the outset, where screens attach and detach command would replace direct use of bg
and fg
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…