In Linux, each terminal is associated with only one session (a session has one or more process groups, and a process group has one or more processes).
Is there some function (or a command) that takes a tty device file (for example: /dev/tty1 or /dev/pts/0) and returns the session id associated with this tty/terminal?
Perform the following steps:
statthe TTY you want to check. In particular, find out the major/minor device id it is using. Combine them to a single number using the formulamajor*256+minor(or just take the raw number fromstat)Open
/proc/and scan all directories whose name is only digits. The directory's name is thepidof a process in the system.For each such directory, open
/proc/pid/stat, and parse the file into fields separated by a space (except the second field, which has brackets around it). The 7th field will be the TTY device's major/minor. Scan until you find one that matches the TTY for which you are looking.The 6th field in that file is the
sidfor the process (the number you're looking for). The 8th field is the TTY'spgrp.File structure detailed here.