Tugger the SLUGger!SLUG Mailing List Archives

[SLUG] Small correction to that "nextx" script


Here's a correction to that script I posted, that tells you the next
available X11 display number, so you can automatically start up
multiple X sessions.

The problem was that a race condition in the ps output could be grabbed
by the sed command, so you got a part of the sed command in the output
stream, which messed up the calculation of the 1st available free X
display number.

Anyway, the corrected script is attached.  I've also added a usage
message.

luke
#!/bin/sh
#
# Determine the next available X display.
#
# Author: Luke Kendall
#
# Copyright: None - placed in the public domain.
#
MYNAME=`basename $0`
USAGE="$MYNAME [-v]
    Where -v means output key sequences for text and graphics consoles
    (on stderr).

    \`$MYNAME' outputs the number of the next available X display, for use
    with startx --:'number'.  The number is output to stdout."
[ $# -ge 2 ] && echo "Usage: $USAGE" >&2 && exit 1

TMPF=/tmp/nx$$
if [ "x$1" = "x-v" ]
then
    verbose=echo
else
    verbose=":"
fi

#
# Output from ps ax, for X, should look something like:
#
# 1551 ?        S      0:02 /etc/X11/X :0 -bpp 16 -auth /home/stella/.Xauthority
#
# So we just grab the display number after the `:'.  The trick is that we
# have to exclude both grep, and especially the sed, that would match our
# own process pattern searches, and mess up the hunt for the X11 processes.
#
ps ax \
    | grep "/X " \
    | egrep -vw "(grep|sed)" \
    | sed 's/^.*\/X ://;s/ .*//' \
    | sort -n > $TMPF

dnum=0
while [ $dnum -lt 4 ]
do
    read actnum
    if [ "$dnum" != "$actnum" ]
    then
	#
	# We've found the lowest display number not in use.
	#
	echo "$dnum"
	$verbose "Your displays will be: Text: Ctrl-Alt-F`expr $dnum + 1`," \
	    "Graphics: Ctrl-Alt-F`expr $dnum + 7`" >&2
	/bin/rm $TMPF
	exit 0
    fi
    dnum=`expr $dnum + 1`
done < $TMPF
/bin/rm $TMPF
echo "4 X displays already in use" >&2
exit 1