How to find out if it works from a terminal or GUI

I am trying to create a class that will behave differently if you use the shell or from the GUI.

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

However, in the constructor, I would like to distinguish spaces between commands and GUI launches.

I can easily achieve this using a parameter that will be passed to the constructor when it is declared, but I want to examine my parameters.

I use C ++ on ubuntu and my GUI uses Qt.

+4
source share
2 answers

The standard C method for determining the presence of an X Window:

#include <stdlib.h> if (NULL == getenv("DISPLAY")) is_gui_present = false; else is_gui_present = true; 
  • this allows you to distinguish between pseudo-terminals in a terminal emulator and the clean start of tty.

If you want to determine if there is a shell at all, or if the application was launched, say, from the file manager, then this is not easy: both cases are simply calling the exec system call from the shell or the file manager / GUI manager (often with the same parameters), you need to explicitly pass the flag to see this.

PS I just found a way to do this: check the environment for the "TERM" variable - it is installed for the shell and is inherited to the Qt program, it is often not installed in the graphical interface. But do not take this as an exact decision!

+6
source

Starting programs from the desktop (double-clicking or from the desktop file / start menu) usually redirects the descriptor of the stdin file to the channel. You may find 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 
+5
source

Source: https://habr.com/ru/post/1443754/


All Articles