Finding the terminal your script is running in - Programming On Unix

Users browsing this thread: 2 Guest(s)
movq
Long time nixers
(03-07-2016, 01:56 AM)venam Wrote: lsof

Good point, that would also make it a little more portable.

(03-07-2016, 01:56 AM)venam Wrote: I tried with a terminal multiplexer, they lead back to the right terminal, so no issues on that part.

Actually, that got me thinking. Is that correct? GNU screen does indeed hold an open fd to /dev/ptmx, but my method above can't find it:
Code:
$ ls -al /proc/14731/fd
ls: cannot open directory '/proc/14731/fd': Permission denied
$ sudo !!
sudo ls -al /proc/14731/fd
total 0
dr-x------ 2 root root   0 Jul  3 16:58 .
dr-xr-xr-x 9 root users  0 Jul  3 16:58 ..
lr-x------ 1 root root  64 Jul  3 17:00 0 -> /dev/null
l-wx------ 1 root root  64 Jul  3 17:00 1 -> /dev/null
l-wx------ 1 root root  64 Jul  3 17:00 2 -> /dev/null
lrwx------ 1 root root  64 Jul  3 16:58 3 -> /dev/pts/3
lrwx------ 1 root root  64 Jul  3 17:00 4 -> 'socket:[1072739]'
lrwx------ 1 root root  64 Jul  3 17:00 5 -> /run/utmp
lrwx------ 1 root root  64 Jul  3 17:00 6 -> /dev/ptmx

Maybe the original problem is not defined very well. What is "the" terminal? Is it supposed to be screen or the xterm that runs screen?

Yes, let's indeed ignore the Linux console for now. It only complicates things. :)

From what I understand, terminal emulators call `openpty()` which gets them a pair of connected file descriptors. The "slave" end is something like `/dev/pts/4` and this is what the shell and other programs see. So, what I'm really looking for would be the "master" end. Meaning, if you run a multiplexer, then that's "the" terminal because this process originally called `openpty()`. (So my script gives the wrong answer, due to missing permissions.)

It's simple to find the slave end because that's STDIN of my script. But how to find the process which holds the corresponding (!) master end? Is that even possible? :/ Even worse: In theory, there could be multiple matching processes because that master file descriptor could be inherited or passed on to other processes (even though that's very unlikely). Traversing the process tree may be a pretty good guess, but it's not necessarily correct.

Whew, this turned out to be way more complicated than I thought.


Messages In This Thread
RE: Finding the terminal your script is running in - by movq - 03-07-2016, 12:41 PM