如何查看从终端或GUI运行

Syn*_*ror 4 c++ linux shell ubuntu qt

我正在尝试构建一个类,如果使用shell或GUI运行,它的行为会有所不同.

它可以使用#include"myclass.h"包含在两个表单中......

但是,在构造函数中,我想区分Shell运行和GUI运行.

我可以使用在声明它时传递给构造函数的参数轻松实现它,但我想探索我的选项.

我在ubuntu上使用C++,我的GUI使用Qt.

Dmy*_*nko 7

确定是否存在X Window的标准C方式:

#include <stdlib.h>

if (NULL == getenv("DISPLAY")) is_gui_present = false;
else is_gui_present = true;
Run Code Online (Sandbox Code Playgroud)
  • 这允许区分终端仿真器和纯tty启动中的伪终端.

如果你想确定是否有shell,或者应用程序是从文件管理器运行的,那么这并不容易:两种情况都只是exec从shell 调用系统调用或文件管理器/ GUI程序运行程序(通常使用相同的参数),您需要显式传递一个标志才能看到它.

PS我刚刚找到了一种方法:检查环境中的变量"TERM" - 它是为shell设置的并且继承到Qt程序,它通常不在GUI程序中设置.但是不要把它作为一个准确的解决方案!


Nik*_* C. 6

从桌面启动程序(双击或从桌面文件/开始菜单)启动程序通常会将其stdin文件描述符重定向到管道.你可以检测到这个:

#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
Run Code Online (Sandbox Code Playgroud)