This is a problem I've been trying to solve on my own for some time without any luck. I'm trying to write a script that (amongst other things) can take an arbitrary PID and map it to TTY device's path (the function I'm writing will return "(notty)" if there isn't an associated TTY).
In my attempt to do the above I've been trying to use the the tty_nr in /proc/[pid]/stat:
tty_nr %d (7) The controlling terminal of the process. (The minor device number is contained in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8.)
I can extract the major and minor numbers, no problem. My issue comes into play when I try to translate that into a device path: Do I just do a
find under /dev for a match and accept the first one? Is there a more elegant way of doing this?
I did find this and it seems that the python script has some sort of mapping of tty_nr numbers to physical paths but I can't find any other part of the script that actually populates this list to see where they're getting their data from to see if I can create a Linux analog. It's also possible that it depends on some BSD-ism but I ran into a brick wall.
Basically, I'm trying to not kick off another process if I can help it. Also, the whole "kick off a process with an unknown number of results but only take the first result" approach seems kind of...kludgy. Since I have to show this code to other people I'd like to have a more or less deterministic way of accomplishing this. I would like some guarantee that if (for any reason) there are multiple device files underneath /dev with that major/minor (kind of a corner case, I know, but it'll bug me) that my code will default to whatever the "official" path to the TTY is.
Of course if my concerns about non-determinism of the extract-then-search method are unfounded, that would be good news, I would just want to understand why they're unfounded. All else fails I guess I could just try restricted searches for common paths (/dev/pts* /dev/tty* etc) before moving onto a sweep of all /dev.