How to check if X server is running?

RomanM picture RomanM · Mar 12, 2009 · Viewed 182.1k times · Source

Is there any way to find out if the current session user is running an Xserver (under Linux) ?

I'v started off with things like:

ps -e | grep X 

but this doesn't work always

and one more thing I tried is checking the $DISPLAY variable

Are there any other ways to check this?

EDIT: Some people suggested using the $DISPLAY variables but what if the user fiddles with this variable ? what if he tries to do something and changes this variable and then when I check it, it no longer reflects an accurate state of the system. Is there no specific way to do this that will always return a correct answer ?

I found that it can be done programatically thus:

#include <X11/Xlib.h> 
int main()
    { exit(XOpenDisplay(NULL) ? 0 : 1);  } 

$ gcc -o xprobe xprobe.c -L/usr/X11R6/lib -lX11 

But I am looking for a script way.

Answer

bobbogo picture bobbogo · Aug 15, 2012

I often need to run an X command on a server that is running many X servers, so the ps based answers do not work. Naturally, $DISPLAY has to be set appropriately. To check that that is valid, use xset q in some fragment like:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi