Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 352
Syntax_Error Avatar asked Dec 09 '22 19:12

Syntax_Error


1 Answers

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!

like image 123
Dmytro Sirenko Avatar answered Dec 11 '22 10:12

Dmytro Sirenko