How to determine the graphical tty in loginctl

Loginctl lists a lot of sessions, and I want programmatically to know which one is a graphical session (e.g. GNOME desktop).

In the example below, I have a GNome desktop session open, an ssh connection open, and a text session (getty) open.

$ loginctl
SESSION  UID USER SEAT  TTY  
      3 1000 user seat0 tty2
    237 1000 user       pts/2
    260 1000 user seat0 tty3

3 sessions listed.
$ 

I can guess that tty2 is the GNome session, because I can switch to it using Ctrl+Alt+F2.
tty3 is the text session (Ctrl+Alt+F3). pts/2 is the remaining ssh session. However, how can a program know which one is which?


Note: I don’t think the following ways are solutions, because they are not rigorous. The user can probably open a new tty and run /usr/libexec/gdm-x-session, which will trick my program

Method 1: run ps -aux | grep /usr/libexec/gdm-x-session, see:

... tty2     Sl+  00:32   0:00 /usr/libexec/gdm-x-session

Method 2: Run lsof /dev/tty2, see:

COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
gdm-x-ses 3271 user    0u   CHR    4,2      0t0   23 /dev/tty2
...
Asked By: Eric Stdlib

||

Ask loginctl for the type of each session:

loginctl show-session -p Type 3

This will show Type=x11 or Type=wayland for graphical sessions.

Answered By: Stephen Kitt
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.