Fork to handle quicklook clients

This commit is contained in:
Kovid Goyal 2025-04-05 13:15:05 +05:30
parent 971ddd64e1
commit 7373d2362a
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 24 additions and 2 deletions

View File

@ -909,18 +909,34 @@ def quicklook_service(path_to_socket: str) -> None:
''' '''
import socket import socket
from contextlib import closing, suppress from contextlib import closing, suppress
from calibre.constants import debug
from calibre.ptempfile import reset_base_dir
from calibre.utils.safe_atexit import remove_file_atexit, reset_after_fork
debug(False)
s = socket.socket(socket.AF_UNIX) s = socket.socket(socket.AF_UNIX)
s.setblocking(True) s.setblocking(True)
s.bind(path_to_socket) s.bind(path_to_socket)
with suppress(KeyboardInterrupt), closing(s): with suppress(KeyboardInterrupt), closing(s):
if path_to_socket and not path_to_socket.startswith('\0'): if path_to_socket and not path_to_socket.startswith('\0'):
from calibre.utils.safe_atexit import remove_file_atexit
remove_file_atexit(path_to_socket) remove_file_atexit(path_to_socket)
s.listen(16) s.listen(16)
while True: while True:
c, addr = s.accept() c, addr = s.accept()
c.setblocking(True) c.setblocking(True)
handle_quicklook_client(c) os.set_inheritable(c.fileno(), True)
if child_pid := os.fork(): # parent
c.close()
os.waitpid(child_pid, 0)
else: # child
os.set_inheritable(c.fileno(), False)
reset_after_fork()
reset_base_dir()
try:
handle_quicklook_client(c)
finally:
c.shutdown(socket.SHUT_RDWR)
c.close()
class Profiler: class Profiler:

View File

@ -66,6 +66,12 @@ def ensure_worker():
return worker return worker
def reset_after_fork():
global worker
atexit.unregister(close_worker)
worker = None
def _send_command(action: str, payload: str) -> None: def _send_command(action: str, payload: str) -> None:
worker = ensure_worker() worker = ensure_worker()
worker.stdin.write(json.dumps({'action': action, 'payload': payload}).encode('utf-8')) worker.stdin.write(json.dumps({'action': action, 'payload': payload}).encode('utf-8'))