Ensure run once using fcntl flock

This commit is contained in:
Mikhail Gordeev 2019-05-23 15:48:06 +03:00
parent 656d832e16
commit 7a53873fc3

View File

@ -5,6 +5,7 @@ from typing import Dict, List
import argparse import argparse
import contextlib import contextlib
import datetime import datetime
import fcntl
import glob import glob
import logging import logging
import os import os
@ -26,6 +27,10 @@ class CB:
data_dir = (os.getenv('XDG_DATA_HOME', data_dir = (os.getenv('XDG_DATA_HOME',
os.path.expanduser('~/.local/share')) os.path.expanduser('~/.local/share'))
+ f'/{PROG}/') + f'/{PROG}/')
self.data_dir = data_dir
self.ensure_run_once()
self.images_dir = data_dir + 'images/' self.images_dir = data_dir + 'images/'
self.work_dir = data_dir + 'work/' self.work_dir = data_dir + 'work/'
self.out_dir = data_dir + 'out/' self.out_dir = data_dir + 'out/'
@ -43,6 +48,15 @@ class CB:
self.log.setLevel(self.log_level) self.log.setLevel(self.log_level)
self.info(f'Start {PROG}') self.info(f'Start {PROG}')
def ensure_run_once(self):
self.lock_file = open(self.data_dir + f'{PROG}.lock', 'w')
try:
fcntl.flock(self.lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError: # already locked
print(f'{PROG} already running', file=sys.stderr)
exit(3)
@contextlib.contextmanager @contextlib.contextmanager
def pushd(self, new_dir): def pushd(self, new_dir):
previous_dir = os.getcwd() previous_dir = os.getcwd()