如何以编程方式(C/C++)验证是否已启用X11转发?

huangapple go评论108阅读模式
英文:

How to programmatically (C/C++) verify if X11 forwarding is enabled?

问题

应用程序在目标硬件上远程运行。用户可以选择启用可视调试输出(使用命令行开关),在这种情况下,使用ssh的X11转发来查看它。

问题在于,如果用户在运行应用程序之前忘记建立连接,就像这样:ssh -YC remote.host,应用程序将崩溃。

我想在启动应用程序时事先检测到这种情况,并打印适当的消息。在C/C++中是否有可能做到这一点?在最坏的情况下,我可以在后台执行一些shell命令。

英文:

The application is run remotely on target hardware. User can choose to enable visual debug output (using command line switches) in that case a ssh's X11 forwarding is used to view it.

The problem starts if user forgets to establish the connection before running the application like this: ssh -YC remote.host. The application will crash.

I would like to detect this situation beforehand and print proper message while starting the application.
Is it possible to do it in C/C++? In the worst case I can execute some shell commands in the background.

答案1

得分: 2

如果您拥有X11显示(真实的或通过ssh转发),您将拥有一个DISPLAY环境变量。否则,它不应该存在。

最不侵入性的检查可能是:

if (!getenv("DISPLAY")) {
    fprintf(stderr, "缺少X11显示,您是否忘记了什么?\n");
    exit(1);
}

如果有人在ssh中忘记了X转发,这应该可以正常触发。

英文:

If you have an X11 display (real or forwarded by ssh), you have a DISPLAY environment variable. Otherwise it should not be present.

The least invasive check is probably:

if (!getenv("DISPLAY")) {
    fprintf(stderr, "missing X11 display, have you forgotten something?\n");
    exit(1);
}

This should trigger just fine if someone forgets X forwarding in ssh.

答案2

得分: 1

你可以使用XOpenDisplay man page

#include <X11/Xlib.h>
#include <cstdlib>
#include <iostream>

bool displayIsValid()
{
    char* disp = getenv("DISPLAY");
    if (disp == nullptr) return false;
    Display* dpy = XOpenDisplay(disp);  
    if (dpy == nullptr) return false;
    XCloseDisplay(dpy);
    return true;
}

int main() {
    if (displayIsValid()) {
        std::cout << "Display is valid" << std::endl;
    }
}
英文:

You could use XOpenDisplay man page

#include &lt;X11/Xlib.h&gt;
#include &lt;cstdlib&gt;
#include &lt;iostream&gt;

bool displayIsValid()
{
    char* disp = getenv(&quot;DISPLAY&quot;);
    if ( disp==nullptr ) return false;
    Display* dpy = XOpenDisplay(disp);  
    if ( dpy==nullptr ) return false;
    XCloseDisplay(dpy);
    return true;
}

int main() {
    if ( displayIsValid() ) {
        std::cout &lt;&lt; &quot;Display is valid&quot; &lt;&lt; std::endl;
    }
}

huangapple
  • 本文由 发表于 2023年3月9日 18:36:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定