File: lock.py

package info (click to toggle)
subuser 0.6.2-3
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 4,208 kB
  • sloc: python: 5,201; sh: 380; makefile: 73
file content (35 lines) | stat: -rwxr-xr-x 756 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# -*- coding: utf-8 -*-

"""
File locking helper functions. Originally taken from https://stackoverflow.com/questions/5255220/fcntl-flock-how-to-implement-a-timeout
"""

#external imports
import os
#internal imports
#import ...
import signal, errno
from contextlib import contextmanager
import fcntl

@contextmanager
def wrapTimeout(seconds):
  def timeout_handler(signum, frame):
    pass

  original_handler = signal.signal(signal.SIGALRM, timeout_handler)

  try:
    signal.alarm(seconds)
    yield
  finally:
    signal.alarm(0)
    signal.signal(signal.SIGALRM, original_handler)

def getLock(fd,timeout=None):
  if not timeout is None:
    with wrapTimeout(timeout):
      return getLock(fd)
  else:
    fcntl.flock(fd, fcntl.LOCK_EX)
    return fd