Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed race condition #45

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions xvfbwrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ class Xvfb(object):
# Maximum value to use for a display. 32-bit maxint is the
# highest Xvfb currently supports
MAX_DISPLAY = 2147483647
SLEEP_TIME_BEFORE_START = 0.1

def __init__(self, width=800, height=680, colordepth=24, tempdir=None, display=None,
**kwargs):
timeout=5, **kwargs):
self.width = width
self.height = height
self.colordepth = colordepth
self._tempdir = tempdir or tempfile.gettempdir()
self._timeout = timeout
self.new_display = display

if not self.xvfb_exists():
Expand Down Expand Up @@ -71,21 +71,24 @@ def start(self):
else:
self.new_display = self._get_next_unused_display()
display_var = ':{}'.format(self.new_display)
self.xvfb_cmd = ['Xvfb', display_var] + self.extra_xvfb_args
with open(os.devnull, 'w') as fnull:
self.proc = subprocess.Popen(self.xvfb_cmd,
stdout=fnull,
stderr=fnull,
close_fds=True)
# give Xvfb time to start
time.sleep(self.__class__.SLEEP_TIME_BEFORE_START)
xvfb_cmd = ['Xvfb', display_var] + self.extra_xvfb_args
self.proc = subprocess.Popen(xvfb_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
close_fds=True)
start = time.time()
while not local_display_exists(self.new_display):
time.sleep(1e-3)
if time.time() - start > self._timeout:
self.stop()
raise RuntimeError('Xvfb display did not open: {}'.format(xvfb_cmd))
ret_code = self.proc.poll()
if ret_code is None:
self._set_display_var(self.new_display)
else:
self._cleanup_lock_file()
raise RuntimeError('Xvfb did not start ({0}): {1}'
.format(ret_code, self.xvfb_cmd))
.format(ret_code, xvfb_cmd))

def stop(self):
try:
Expand All @@ -96,7 +99,7 @@ def stop(self):
if self.proc is not None:
try:
self.proc.terminate()
self.proc.wait()
self.proc.wait(self._timeout)
except OSError:
pass
self.proc = None
Expand Down Expand Up @@ -163,3 +166,7 @@ def _get_next_unused_display(self):

def _set_display_var(self, display):
os.environ['DISPLAY'] = ':{}'.format(display)


def local_display_exists(display):
return os.path.exists('/tmp/.X11-unix/X{}'.format(display))