A cheap and easy way to see if the X server is running is to just try to connect to it. If the connection works, then X is running (probably) otherwise it is not running. (This would fail if some other program is listening to the same port as X uses.)

First, you'll need $ENV{DISPLAY}. If it isn't there, then X is not running. The format of DISPLAY is "hostname:display.screen" where display and screen are numbers, and screen is optional. If hostname is not there, it defaults to localhost. Common settings are "localhost:0" and "localhost:0.0" or just ":0"

Once you have the hostname and the display number, add 6000 to the display number and attempt to make a TCP connection to that port number. If the connection fails, X is not running. If it works, just disconnect immediately and assume you connected to the X server. (For extra credit, you might try sending data into the connection and see if you get the right reply back.)

UPDATE: This method does not always work. The user's X server may not be listening on TCP. When DISPLAY=":0.0" then the "most efficient way of communicating to a server on the same machine" should be used. Usually that means UNIX domain sockets, but it is platform dependent. In this case, the TCP connection fails even though there is a running X server.


In reply to Re: How to detect X? by bunnyman
in thread How to detect X? by blazar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.