检查 X11 扩展

Check for X11 extension

我正在编写一个 shell 脚本,该脚本需要改变其行为并根据特定 X11 扩展的存在与否为调用的程序提供不同的选项。我有一个可行的解决方案,但我希望有一个更清洁的解决方案。我愿意考虑一个简单的 c 程序来进行测试和 return 结果。这是我作为最小功能示例工作的内容:

#!/bin/sh
xdpyinfo |sed -nr '/^number of extensions/,/^[^ ]/s/^  *//p'  | \
    grep -q $EXTENSION && echo present

我认为有一种方法可以简化 sed、grep,但我真的不想解析 xdpyinfo

你也有 C-tag,所以我建议你自己做 xdpyinfo。以下 C 程序仅打印扩展名:

#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int compare(const void *a, const void *b)
{
  return strcmp(*(char **) a, *(char **) b);
}

static void print_extension_info(Display * dpy)
{
  int n = 0, i;
  char **extlist = XListExtensions(dpy, &n);


  printf("number of extensions:    %d\n", n);
  if (extlist) {
    qsort(extlist, n, sizeof(char *), compare);
    for (i = 0; i < n; i++) {

      printf("    %s\n", extlist[i]);

    }
  }
  // TODO: it might not be a good idea to free extlist, check
}

int main()
{
  Display *dpy;
  char *displayname = NULL;

  dpy = XOpenDisplay(displayname);
  if (!dpy) {
    fprintf(stderr, "Unable to open display \"%s\".\n",
            XDisplayName(displayname));
    exit(EXIT_FAILURE);
  }

  print_extension_info(dpy);

  XCloseDisplay(dpy);
  exit(EXIT_SUCCESS);
}

用例如 GCC 编译

gcc -O3 -g3  -W -Wall -Wextra  xdpyinfo1.0.2.c  $(pkg-config --cflags --libs x11)  -o xdpyinfo1.0.2

(应该对未使用的 argc 发出警告,但这是无害的)

只需将 printf() 更改为您想要的格式即可。