I have seen in many programs, almost only on linux, that when you run the program with a graphical manager(Clicking the executable) the program runs in a graphical window and when you run it from the terminal it runs on text mode.
I want to know how to do that.
Does anyone know how?
3
It is operating system specific.
On Linux with X11, you could simply use the fact that DISPLAY
is an unset environment variable outside of graphical desktop interfaces (or test for the success of XOpenDisplay
);
You might also use isatty(3) on STDIN_FILENO
(which is 0) to test if stdin is a terminal (but you could also open /dev/tty
and see if it fails, cf tty(4))
so simply code
if (getenv("DISPLAY"))
startmyGUIapplication();
else if (isatty(STDIN_FILENO))
startmyterminalapplication();
else
error(); // application started outside, e.g. from `crontab`
Regarding Qt, I guess that QApplication would fail to be constructed if not used in a GUI, Or its exec function would fail.
PS. On Linux with a Wayland desktop (or on MacOSX with Quartz), I don’t know how to do that, but I am sure there is a simple solution.