简体   繁体   English

如何查看从终端或GUI运行

[英]how to find out if running from terminal or GUI

I am trying to build a class that would behave is a different way if run using a shell or from a GUI. 我正在尝试构建一个类,如果使用shell或GUI运行,它的行为会有所不同。

It could be included in both forms using #include "myclass.h"... 它可以使用#include“myclass.h”包含在两个表单中......

However, in the constructor I would like to differentiate between Shell runs and GUI runs. 但是,在构造函数中,我想区分Shell运行和GUI运行。

I can easily achieve it using a parameter that would be passed to the constructor when declaring it but I want to explore my options. 我可以使用在声明它时传递给构造函数的参数轻松实现它,但我想探索我的选项。

I am using C++ on ubuntu and my GUI is using Qt. 我在ubuntu上使用C ++,我的GUI使用Qt。

The standard C way of determining whether X Window is present: 确定是否存在X Window的标准C方式:

#include <stdlib.h>

if (NULL == getenv("DISPLAY")) is_gui_present = false;
else is_gui_present = true;
  • this allows to distinguish pseudo-terminals in terminal emulator and pure tty launch. 这允许区分终端仿真器和纯tty启动中的伪终端。

If you want to determine if there is a shell at all, or the application was run from, say, a file manager, then it's not easy: both cases are just call of exec system call from a shell or a file manager/GUI program runner (often with the same parameters), you need to pass a flag explicitly to see that. 如果你想确定是否有shell,或者应用程序是从文件管理器运行的,那么这并不容易:两种情况都只是调用来自shell或文件管理器/ GUI程序的exec系统调用运行器(通常具有相同的参数),您需要显式传递一个标志才能看到它。

PS I've just found a way to do that: check the environment for variable "TERM" - it is set for a shell and is inherited to Qt program, it is often not set in a GUI program. PS我刚刚找到了一种方法:检查环境中的变量“TERM” - 它是为shell设置的并且继承到Qt程序,它通常不在GUI程序中设置。 But don't take this as an accurate solution! 但是不要把它作为一个准确的解决方案!

Launching programs from the desktop (double click or from a desktop file/start menu) will usually redirect their stdin file descriptor to a pipe. 从桌面启动程序(双击或从桌面文件/开始菜单)启动程序通常会将其stdin文件描述符重定向到管道。 You can detect this: 你可以检测到这个:

#include <cstdio>    // fileno()
#include <unistd.h>  // isatty()

if (isatty(fileno(stdin)))
    // We were launched from the command line.
else
    // We were launched from inside the desktop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM