How to check if X server is running?

2019-03-08 22:04发布

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.

12条回答
Viruses.
2楼-- · 2019-03-08 22:44

I wrote xdpyprobe program which is intended for this purpose. Unlike xset, xdpyinfo and other general tools, it does not do any extra actions (just checks X server and exits) and it may not produce any output (if "-q" option is specified).

查看更多
小情绪 Triste *
3楼-- · 2019-03-08 22:45

You can use xdpyinfo (can be installed via apt-get install x11-utils).

查看更多
在下西门庆
4楼-- · 2019-03-08 22:47

The bash script solution:

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

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

查看更多
放我归山
5楼-- · 2019-03-08 22:48
if [[ $DISPLAY ]]; then 
  …
fi
查看更多
The star\"
6楼-- · 2019-03-08 22:48

This is PHP script for checking.

$xsession = `pidof X`;
if (!$xsession) {
    echo "There is no active X session, aborting..\n";
    exit;
}

Similar command can be used in shell script too. like the pidof command.

查看更多
The star\"
7楼-- · 2019-03-08 22:51
xprop -root &> /dev/null 

...is my tried & true command to test for an "X-able" situation. And, it's pretty much guaranteed to be on any system running X, of course, the command fails if not found anyways, so even if it doesnt exist, you can pretty much assume there is no X either. (thats why I use &> instead of >)

查看更多
登录 后发表回答