how to find out if running from terminal or GUI

c++, linux, qt, shell, ubuntu

Solution

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!

Problem

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.

Original source