From 1a9be279c6d7b1b4393c327bcc8851028dd23c4b Mon Sep 17 00:00:00 2001 From: Daniel Pavel Date: Sun, 28 Apr 2013 14:06:41 +0200 Subject: [PATCH] move the code for single-instance check into its own file --- lib/solaar/appinstance.py | 47 +++++++++++++++++++++++++++++++++++++++ lib/solaar/gtk.py | 35 ++++------------------------- 2 files changed, 51 insertions(+), 31 deletions(-) create mode 100644 lib/solaar/appinstance.py diff --git a/lib/solaar/appinstance.py b/lib/solaar/appinstance.py new file mode 100644 index 00000000..74601aa6 --- /dev/null +++ b/lib/solaar/appinstance.py @@ -0,0 +1,47 @@ +# +# +# + +from __future__ import absolute_import, division, print_function, unicode_literals + +# +# +# + +import fcntl as _fcntl +import os.path as _path +import os as _os + + +def check(): + # ensure no more than a single instance runs at a time + lock_fd = None + for p in _os.environ.get('XDG_RUNTIME_DIR'), '/run/lock', '/var/lock', _os.environ.get('TMPDIR', '/tmp'): + if p and _path.isdir(p) and _os.access(p, _os.W_OK): + lock_path = _path.join(p, 'solaar.single-instance.%d' % _os.getuid()) + try: + lock_fd = open(lock_path, 'wb') + # print ("Single instance lock file is %s" % lock_path) + break + except: + pass + + if lock_fd: + try: + _fcntl.flock(lock_fd, _fcntl.LOCK_EX | _fcntl.LOCK_NB) + return lock_fd + except IOError as e: + if e.errno == 11: + import sys + sys.exit("solaar: error: Solaar is already running.") + else: + raise + else: + import sys + print ("solaar: warning: failed to create single instance lock file, ignoring.", file=sys.stderr) + + +def close(lock_fd): + if lock_fd: + _fcntl.flock(lock_fd, _fcntl.LOCK_UN) + lock_fd.close() diff --git a/lib/solaar/gtk.py b/lib/solaar/gtk.py index 82427104..be9c0355 100644 --- a/lib/solaar/gtk.py +++ b/lib/solaar/gtk.py @@ -125,40 +125,13 @@ def main(): _require('gi.repository.Gtk', 'gir1.2-gtk-3.0') args = _parse_arguments() - # ensure no more than a single instance runs at a time - import os.path as _path - import os as _os - lock_fd = None - for p in _os.environ.get('XDG_RUNTIME_DIR'), '/run/lock', '/var/lock', _os.environ.get('TMPDIR', '/tmp'): - if p and _path.isdir(p) and _os.access(p, _os.W_OK): - lock_path = _path.join(p, 'solaar.single-instance.%d' % _os.getuid()) - try: - lock_fd = open(lock_path, 'wb') - # print ("Single instance lock file is %s" % lock_path) - break - except: - pass - - if lock_fd: - import fcntl as _fcntl - try: - _fcntl.flock(lock_fd, _fcntl.LOCK_EX | _fcntl.LOCK_NB) - except IOError as e: - if e.errno == 11: - import sys - sys.exit("solaar: error: Solaar is already running.") - else: - raise - else: - import sys - print ("solaar: warning: failed to create single instance lock file, ignoring.", file=sys.stderr) - + from . import appinstance + appid = appinstance.check() try: _run(args) finally: - if lock_fd: - _fcntl.flock(lock_fd, _fcntl.LOCK_UN) - lock_fd.close() + appinstance.close(appid) + if __name__ == '__main__': main()