Use Terminal with X11, revisited

Sep 14, '05 09:10:00AM

Contributed by: marcelk

This hint evolved from two earlier hints: Stop automatic xterm in Apple X11 and Use other terminal apps with Apple's X11.

Like many others, I want to use X11 apps occasionally without needing to start X11 manually when that is needed. However, I also don't want to get the automatic xterm that Apple launches when X11 starts. Further, I don't want to modify /etc/X11/xinit/xinitrc directly (it is a system file!), but I also don't feel comfortable cloning this file into my home directory and making modifications there. If there are system updates, for instance, you won't see them otherwise. Finally, new terminals should detect when DISPLAY is not set, and have it point to the current user's X server. (Also in the presence of multiple users running X11.) In other words, it should just work.

One comment in the second hint referenced above suggested a way to start X11 from .profile, as long as X11 is not running yet. But that involves refocussing the window, which I find a bit clumsy. So I just start X11 the normal way, from System Preferences -> Accounts -> Login Items. I don't mind having it hanging around all the time -- X11 is very small when is has no windows running.

The trick is that my ~/.xinitrc surpresses the initial xterm, still runs the system's initrc, and records the display in ~/tmp/X11-display-hostname (for later lookup by starting terminals). Here it is:

.xinitrc

# surpress starting of an initial xterm
xterm()
{
    return 0
}

# remember the display name
echo "$DISPLAY" > $HOME/tmp/X11-display-`hostname -s`

# run system-defined xinitrc (doesn't return)
source /etc/X11/xinit/xinitrc
I keep temporary information in a private tmp directory. Create one with mkdir ~/tmp ; chmod 700 ~/tmp. Finally, .profile checks if it needs to connect to an X11. If DISPLAY is already set, it doesn't touch it (so X11 forwarding with ssh still works). It also tests if the X11 server is still alive. Here is the snippet in .profile:

.profile
PATH=/usr/X11R6/bin:$PATH

if [ ! $SSH_TTY ] && [ ! $DISPLAY ]
then
    DISPLAY=`cat $HOME/tmp/X11-display-`hostname -s` 2>/dev/null`
    if xwininfo -display "$DISPLAY" -root >/dev/null 2>&1
    then
        export DISPLAY
    else
        echo X11 display $DISPLAY not active
        unset DISPLAY
        rm -f $HOME/tmp/X11-display-`hostname -s`
    fi
fi
That's it! Now all my Terminals are automatically aware of the X11 server, and I have no annoying xterm window during startup.

Comments (14)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2005091004025818