When X starts, it searches for the lowest unused VT, and attaches to it. My problem is that when there are several running X processes, I need to be able to identify which one is the currently active one.
This is a *BSD question, because on linux it's easy: X sets its controlling terminal to be
ttyN, or, on very old distributions, it's specified on the commandline as
vtN. So, I'm running a service and I see that the currently active VT is
tty7, and there are two X servers running, it's easy to tell which one corresponds to the current terminal. (This is a reasonable case: perhaps the user used GNOME/KDE's 'switch user' functionality or ran two servers using
startx.) An example application that might want to follow the active X server is
x11vnc (which is forked from the software I'm developing).
On FreeBSD though, the controlling terminal does not tell you anything. When X is started from ttyv1, that remains the controlling terminal.
I've done due diligence and read the X code. After some hunting around, it's now clearer to me what's going on.
In lnx_init.c, the X server does
setsid to make a fresh session for itself, then opens an fd to
ttyN straight after to do a
VT_ACTIVATE ioctl on it. Pretty standard; opening the fd to a terminal with no controlling process from a process with no controlling terminal associates the two, and the server keeps the fd open, so it's guaranteed that the terminal will remaining the controlling terminal for the X server.
Now, in bsd_init.c, opening the fd to the tty to be used as the framebuffer doesn't make it a controlling terminal (and in fact, with no
setsid, BSD Xserver started from
xinit on ttyv2 will keep ttyv2 as its ctty!).