如何以编程方式testing是否可以连接到$ DISPLAY中指定的X服务器

这在编程和服务器pipe理之间有点中间地带,但是这似乎最终是最相关的地方。

我正在寻找一种方法来确定variables' $DISPLAY '是否宣传我们可以实际连接到的XServer,也就是说,如果所有的身份validation和任何东西都已到位,以允许执行更多的事情。

我理想的是寻找一些shell-end工具返回true / false,这可以在构build脚本中使用,以确定是否应该运行其中的其他testing(我不能控制)。

目前的testing只是检查envvariables“ $DISPLAY ”,如果它在那里,将尝试连接,并且当连接不起作用时,testing假定testing失败,而不仅仅是显示不可连接。

我只需要能够做到

 if [[ ! can_connect_to_X ]] ; then unset DISPLAY fi 

为了停止这些testing有严重的精神问题。

在理想的情况下,需要这样做的工具应该由X客户端库本身提供,以免产生特殊的依赖关系,并且假设实用工具不在那里,我们不能连接到任何显示器。

您可以尝试使用xset命令:

 if [[ ! $(xset -q) ]]; then # the X server is not reachable else # the X server is reachable fi 

我猜测有一个更好的解决scheme。 但是你总是可以使用像xclock这样的小工具来检查退出状态。

 if [[ ! xclock ]]; then exit 1 fi pkill xclock 

但是,男人,这丑陋的:-)

less了Hacky,把下面的代码放在checkX.c中:

 #include <X11/Xlib.h> #include <stdio.h> int main() { Display *display; if( ! (display=XOpenDisplay(NULL) ) ) { return(1); } return 0; } 

然后:

 gcc -lX11 checkX.c -o checkX chmod +x checkX 

最后:

 if ./checkX; then echo "We are good to go!" fi 

inheritance人可能WayToDoIt,但不知道它有多好。

  x_works(){ # If there is no xdpyinfo # Bash will return 127 # If X cant connect, it returns 1 # If X can connect, it returns 0 xdpyinfo 1>/dev/null 2>&1 WORKS="$?" return $WORKS } if x_works; then ... 

似乎是工作。