mr_dont has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

I am trying to write a script that acts as a command line program when X is not running, but has a GUI when it sees that X is up.

The only way I can think of doing this is to maybe look at TCP/IP ports (or something like that) to detect if X is up or not.

Any ideas about how I can do this? I have no idea where to start!

Thanks, fellow monks...

Replies are listed 'Best First'.
Re: Checking X server status
by bikeNomad (Priest) on Jun 25, 2001 at 23:52 UTC
    Nothing that our friend Inline can't cure:

    #!/usr/bin/perl -w use strict; use Inline(C => Config => INC => '-I/usr/local/include', AUTO_INCLUDE => '#include <X11/Xlib.h>', LIBS => '-L/usr/X11R6/lib -lX11', CCFLAGS => '-O2' ); use Inline C => <<'END_OF_C_CODE'; int isXRunning() { Display* display; char* displayName; int retval = 0; displayName = getenv("DISPLAY"); if (!displayName) { displayName = "localhost:0"; } display = XOpenDisplay(displayName); if (display) { XCloseDisplay(display); retval = 1; } return retval; } END_OF_C_CODE print isXRunning() ? "X is running\n" : "What X?\n";
Re: Checking X server status
by the_slycer (Chaplain) on Jun 25, 2001 at 23:47 UTC
    Or check to see if the $ENV{DISPLAY} variable is set. If it is, X is running, if not, X is not running.
      No, you can have $DISPLAY set and not have X running. I've seen $DISPLAY set by login scripts before (not uncommon when the display is on a remote machine). Try this from a text console without X running:
      bash$ export DISPLAY=localhost:0 bash$ echo $DISPLAY

      Remember, your X server may not be on the local machine. I keep my $DISPLAY variable set on my embedded machines so I can run X programs on them at will, but don't actually start window managers for them, so most of the time $DISPLAY is set but the server might or might not be available.

      Also, you can have X running but not have a $DISPLAY environment variable set (like if you go to a text console on the same machine).

      This brings up the question of "what do you mean 'X running'?". Do you mean: is there one or more X servers going on this or some other machine, or is this program being run from within an X session? These are both tricky. My program just looks for a running X server at either $DISPLAY or localhost:0; if a server is not available, it returns 0.

      Oh yeah...

      I guess i need to read up on how X works! Thanks for the tips, monks!

Re: Checking X server status
by DrSax (Sexton) on Jun 25, 2001 at 23:32 UTC
    Can't you just have your program do a grep Xsession to determine if the session is running?

    DrSax