英文:
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 <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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论