Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Don't setup unmonitored pipes to child processes. #1360

Merged
merged 3 commits into from
Feb 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 33 additions & 7 deletions ulauncher/utils/launch_detached.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import os
import sys

from gi.repository import GLib

Expand All @@ -8,12 +9,38 @@
logger = logging.getLogger()


def detach_child():
"""
A utility function which runs in the child process launched by spawn_async
and before execing the supplied command.
"""
# Use setsid to take "session leader" status so that the child pid is
# definitely detached from the parent ulauncher process
os.setsid()

# Don't redirect the standard file descriptors unless connected to a terminal.
if not sys.stdout.isatty():
return

# Reopen the stdin, stdout, and stderr file descriptors to /dev/null. This
# ensures the stdout/stderr are no longer connected to the terminal. This
# serves a similar purpose as the standard "nohup" command. Any processes
# connected to the terminal will get the interrupt signal when "Ctrl-C" is
# called, so this redirection prevents the child process from exiting when
# ulauncher is interrupted. Unlike "nohup", stdout and stderr are not sent
# to a file but sent to /dev/null instead.
null_fp = open("/dev/null", "w+b") # noqa: SIM115
null_fd = null_fp.fileno()
for fp in [sys.stdin, sys.stdout, sys.stderr]:
orig_fd = fp.fileno()
fp.close()
os.dup2(null_fd, orig_fd)


def launch_detached(cmd):
cmd = (
["systemd-run", "--user", "--scope", *cmd]
if SystemdController("ulauncher").is_active()
else ["setsid", "nohup", *cmd]
)
use_systemd_run = SystemdController("ulauncher").is_active()
if use_systemd_run:
cmd = ["systemd-run", "--user", "--scope", *cmd]

env = dict(os.environ.items())
# Make sure GDK apps aren't forced to use x11 on wayland due to ulauncher's need to run
Expand All @@ -27,8 +54,7 @@ def launch_detached(cmd):
argv=cmd,
envp=envp,
flags=GLib.SpawnFlags.SEARCH_PATH_FROM_ENVP | GLib.SpawnFlags.SEARCH_PATH,
standard_output=True,
standard_error=True,
child_setup=None if use_systemd_run else detach_child,
)
except Exception:
logger.exception('Could not launch "%s"', cmd)
Expand Down