1

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?

  • Is your terminal started within a GUI (e.g some gnome-terminal) ? – Basile Starynkevitch Mar 23 '15 at 6:48
  • 1
    Usually they're different executables, the GUI one wrapping either the command line app or a shared library that does the work. – gbjbaanb Mar 23 '15 at 9:24
  • BTW, the canonical way on Linux to start a program is thru the command line. A lot of Linux programs (e.g. GCC ...) don't have desktop icons or menu entries, and your system could have several GUI programs which have no visual counterpart on your desktop. – Basile Starynkevitch Mar 24 '15 at 7:47
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.