how to find out if running from terminal or GUI

2020-06-23 05:40发布

I am trying to build a class that would behave is a different way if run using a shell or from a GUI.

It could be included in both forms using #include "myclass.h"...

However, in the constructor I would like to differentiate between Shell runs and GUI runs.

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.

2条回答
乱世女痞
2楼-- · 2020-06-23 06:21

Launching programs from the desktop (double click or from a desktop file/start menu) will usually redirect their stdin file descriptor to a pipe. 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
查看更多
一夜七次
3楼-- · 2020-06-23 06:27

The standard C way of determining whether X Window is present:

#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.

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.

P.S. 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. But don't take this as an accurate solution!

查看更多
登录 后发表回答