Files

88 lines
2.5 KiB
Python

"""Platform helpers for the standalone distribution; POSIX behavior is preserved."""
from __future__ import annotations
import errno
import os
import signal
import time
IS_WINDOWS = os.name == 'nt'
if os.name != 'nt':
import fcntl
else:
import msvcrt
class _FileLocks:
LOCK_EX, LOCK_NB, LOCK_UN = 2, 4, 8
@staticmethod
def flock(fd, operation):
os.lseek(fd, 0, os.SEEK_SET)
if operation & _FileLocks.LOCK_UN:
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
return
while True:
try:
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
return
except OSError as error:
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
if operation & _FileLocks.LOCK_NB:
raise BlockingIOError(errno.EAGAIN, 'File is locked') from None
time.sleep(.05)
fcntl = _FileLocks()
def private_bits(mode):
# NTFS access is protected by the inherited user-only ACL on .runtime.
# Windows' st_mode has no information about that ACL.
return not IS_WINDOWS and bool(mode & 0o077)
def owner_mismatch(info):
return not IS_WINDOWS and info.st_uid != os.getuid()
def fchmod(fd, mode):
if os.name != 'nt':
os.fchmod(fd, mode)
def ps_value(pid, field):
import psutil
try:
process = psutil.Process(int(pid))
if not process.is_running() or process.status() == psutil.STATUS_ZOMBIE:
return None
if field == 'lstart':
return repr(process.create_time())
if field == 'command':
return ' '.join(process.cmdline())
return None
except (psutil.Error, ValueError):
return None
def group_leader(pid):
return True if os.name == 'nt' else os.getpgid(pid) == pid
def killpg(pid, sig):
if os.name != 'nt':
return os.killpg(pid, sig)
import psutil
try:
process = psutil.Process(pid)
# Caller verifies creation time and executable before reaching this point.
children = process.children(recursive=True)
for child in reversed(children):
try:
child.kill() if sig == getattr(signal, 'SIGKILL', 9) else child.terminate()
except psutil.NoSuchProcess:
pass
process.kill() if sig == getattr(signal, 'SIGKILL', 9) else process.terminate()
except psutil.NoSuchProcess:
raise ProcessLookupError(pid) from None