in reply to X or console?

I made a quickie module (sorry, can't post it) for work. A first-check is for the environment variable DISPLAY. If you don't have it, the user's not accessing the shell with an X service available. This is pseudocode:
sub hasX { return undef if not defined $ENV{DISPLAY}; return undef if port_not_listening($ENV{DISPLAY}); return 1; }
It's not foolproof. But after you get a hint from these, you can look at CPAN's X11 modules for more support.

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: X or console?
by bobn (Chaplain) on Jul 23, 2003 at 18:53 UTC

    What is your port_not_listening()? here's mine:

    sub port_not_listening { # UNTESTED my $timeout = 10; my ($remote, $port) = split(/:/, $_[0]); $iaddr = inet_aton($remote) or return 1; $paddr = sockaddr_in($port, $iaddr); $proto = getprotobyname('tcp'); # X uses tcp, right? socket(SOCK, PF_INET, SOCK_STREAM, $proto) or die "socket: $!"; eval { local $SIG{ALRM} = sub { die "connection timeout\n" }; alarm $timeout; connect(SOCK, $paddr) or die "$! for $remote\n"; alarm 0; }; return 1 if ( $@ ); return 0; }

    Update: Halley points out correctly (below) that the line my ($remote, $port) = split(/:/, $_[0]); is unlikely to actually yield a correct port number.

    --Bob Niederman, http://bob-n.com
      Generally, $ENV{DISPLAY} isn't going to give an exact port number. The typical X11 setup assumes (TCP 6000 + $port) where $port is what you find in the variable. There are more complicated port configurations like "localhost:1.1", though, so I didn't go into lengthy discussion. Use the X11 modules which presumably do it right.

      --
      [ e d @ h a l l e y . c c ]

        Theat's the part that's untested. Damn, I remembered the colon, but forgot that wat's after it is frequently some number that would be silly at best as a port number. (I think I confused it with the way X connections tunneld in ssh look in netstat output, which is on the order of localhost:6012). DRAT!

        Given a correct IP and port, the rest of the code should be good because it's extracted from code I actually use. But the ($addr, $port) = split(/:/, $ENV{DISPLAY}) is almost certain not to yiled a good port.

        --Bob Niederman, http://bob-n.com