Fix use of single instance with detach

This commit is contained in:
Kovid Goyal
2025-04-24 07:17:55 +05:30
parent bd0116b561
commit 867ec83bed
3 changed files with 24 additions and 11 deletions

View File

@@ -349,9 +349,14 @@ def handle_single_instance_command(boss: BossType, sys_args: Sequence[str], envi
def main(sys_args: list[str]) -> None:
global args
args, items = parse_panel_args(sys_args[1:])
talk_fd = -1
if args.single_instance:
si_data = os.environ.get('KITTY_SI_DATA', '')
if si_data:
talk_fd = int(si_data)
if args.detach:
from kitty.utils import detach
detach(log_file=args.detached_log or os.devnull)
detach(talk_fd, log_file=args.detached_log or os.devnull)
sys.argv = ['kitty']
if args.debug_rendering:
sys.argv.append('--debug-rendering')

View File

@@ -504,20 +504,21 @@ def _main() -> None:
cli_opts.args = []
else:
cli_opts.args = rest
if cli_opts.detach:
if cli_opts.session == '-':
from .session import PreReadSession
cli_opts.session = PreReadSession(sys.stdin.read(), os.environ)
detach()
if cli_opts.replay_commands:
from kitty.client import main as client_main
client_main(cli_opts.replay_commands)
return
talk_fd = -1
if cli_opts.single_instance:
si_data = os.environ.pop('KITTY_SI_DATA', '')
if si_data:
talk_fd = int(si_data)
if cli_opts.detach:
if cli_opts.session == '-':
from .session import PreReadSession
cli_opts.session = PreReadSession(sys.stdin.read(), os.environ)
detach(talk_fd)
if cli_opts.replay_commands:
from kitty.client import main as client_main
client_main(cli_opts.replay_commands)
return
bad_lines: list[BadLine] = []
opts = create_opts(cli_opts, accumulate_bad_lines=bad_lines)
setup_environment(opts, cli_opts)

View File

@@ -257,11 +257,18 @@ def open_url(url: str, program: str | list[str] = 'default', cwd: str | None = N
return open_cmd(command_for_open(program), url, cwd=cwd, extra_env=extra_env)
def detach(fork: bool = True, setsid: bool = True, redirect: bool = True, log_file: str = os.devnull) -> None:
def detach(*preserve_fds: int, fork: bool = True, setsid: bool = True, redirect: bool = True, log_file: str = os.devnull) -> None:
reset = []
for fd in preserve_fds:
if fd > -1 and not os.get_inheritable(fd):
os.set_inheritable(fd, True)
reset.append(fd)
if fork:
# Detach from the controlling process.
if os.fork() != 0:
raise SystemExit(0)
for fd in reset:
os.set_inheritable(fd, False)
if setsid:
os.setsid()
if redirect: