Looking for a reliable means of detecting if an application has been launched from a desktop

I have a program that should behave a little bit differently if run from terminal or desktop. If I launch from the desktop I’m looking for a message box pop up, and if run from terminal a simple yes/no command prompt.

So, there’s three things I need to detect. If running on a headless system it should just exit, and if there is an actual user present show a dialogue choice.

I know about getenv("DISPLAY") for detecting whether there is a monitor or not, and isatty(filno(stdin)) for detecting whether an application was launched through a pipe, which is how most of the Linux desktops launch applications.

Is there a more standardized or reliable means of detecting desktop or terminal launch?

If you have some degree of control over the desktop environment, then what you could do is place a desktop launcher somewhere that desktop users will find convenient, and have that launcher pass an argument (’-d’ or something) to the program. Within the program then all you need to do is check argv. If the argument is present, it was a desktop launch. If it’s not, it was a terminal launch. That would be a bullet-proof approach.

If you don’t have any control over the desktop environment, then you might want to get the program to do a ps system call. If you do a ps -o tty --no-headers -p PID on the program’s PID then the response will be ‘pts/#’ if the program was launched from the terminal and something different (’?’ or ‘tty#’ probably) if it was launched from the desktop (depending on what sort of program it is).

Hmm, that later one might work, as I cannot agree my desktop file will be distributed with the program.

It’s Unreal, and they do not provide a canonical desktop file.

Not sure about Unreal games or how you are distributing it, but pretty-much all Steam games return ‘tty#’ as a result of ps -o tty --no-headers -p PID.

Doesn’t really matter though. All terminal/SSH launches will return ‘pts/#’ so that’s all you really need to check for.

Good luck!