4

I'm writing a script that launches a virtual framebuffer with Xvfb. I want to make sure the command succeeds, but I don't want the script to wait until the command completes, because Xvfb continues running until the X server is killed. For example:

if ! Xvfb $DISPLAY &; then
    echo 'Error: failed to create virtual frame buffer'
    exit 1
fi

xpid=$!

# do stuff that uses frame buffer

kill $xpid

The problem with this is it throws a syntax error on &;:

$ stuff.sh 
stuff.sh: line 149: syntax error near unexpected token `;'
stuff.sh: line 149: `if ! Xvfb $DISPLAY &; then'

I tried changing that line to if ! Xvfb $DISPLAY & ; but it still throws the error.

Big McLargeHuge
  • 3,044
  • 11
  • 35
  • 49
  • try removing `;` and shift `then` to next line. – Siva Jul 09 '18 at 17:32
  • 2
    Why not `xvfb-run`? It would run the commands that need the server only after the server successfully started. It would be safer than waiting some guessed amount of time. – JoL Jul 09 '18 at 21:37
  • @JoL I didn't know about it, but that's what I was looking for initially. Thanks! – Big McLargeHuge Jul 10 '18 at 13:28

1 Answers1

9

The & symbol is a control operator and ends the list of commands to be tested. Following that definition, the following is free of syntax errors:

if ! Xvfb $DISPLAY & then
    echo 'Error: failed to create virtual frame buffer'
    exit 1
fi

The trouble is, by backgrounding the Xvfb command, the test result will always be zero/true.

I would start the process, then wait long enough for it to die, then check to see if it is still around:

Xvfb $DISPLAY &
xvfbpid=$!
sleep 3 ## adjust to taste
if ! ps -p $xvfbpid > /dev/null
then
  echo 'Error: failed to create virtual frame buffer'
  exit 1
fi

References:

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
  • 2
    Using `kill -0 "$xvfbpid"` would also test whether the given PID was alive. – Kusalananda Jul 10 '18 at 09:52
  • 1
    There's a theoretical risk that the process could end and a new process re-use that pid before the test. It's really never going to happen in just three seconds, but it's worth mentioning for when folk transfer this to situations of much longer duration. – Toby Speight Jul 08 '23 at 09:10