From e831032c725ce2d4bc63f0bf1ecf33364cf72dac Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 20 Dec 2020 11:46:59 -0800 Subject: [PATCH] wezterm: close random fds when starting wezterm-gui Let's try to eliminate garbage that the OS gui system leaks into us when it spawns wezterm. --- pty/src/unix.rs | 27 ++++++++++++++++++--------- wezterm/src/main.rs | 1 + 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/pty/src/unix.rs b/pty/src/unix.rs index 4409f3c2f..470910b86 100644 --- a/pty/src/unix.rs +++ b/pty/src/unix.rs @@ -98,15 +98,24 @@ impl Read for PtyFd { } } -// On Big Sur, Cocoa leaks various file descriptors to child processes, -// so we need to make a pass through the open descriptors beyond just the -// stdio descriptors and close them all out. -// This is approximately equivalent to the darwin `posix_spawnattr_setflags` -// option POSIX_SPAWN_CLOEXEC_DEFAULT which is used as a bit of a cheat -// on macOS. -// On Linux, gnome/mutter leak shell extension fds to wezterm too, so we -// also need to make an effort to clean up the mess. -fn close_random_fds() { +/// On Big Sur, Cocoa leaks various file descriptors to child processes, +/// so we need to make a pass through the open descriptors beyond just the +/// stdio descriptors and close them all out. +/// This is approximately equivalent to the darwin `posix_spawnattr_setflags` +/// option POSIX_SPAWN_CLOEXEC_DEFAULT which is used as a bit of a cheat +/// on macOS. +/// On Linux, gnome/mutter leak shell extension fds to wezterm too, so we +/// also need to make an effort to clean up the mess. +/// +/// This function enumerates the open filedescriptors in the current process +/// and then will forcibly call close(2) on each open fd that is numbered +/// 3 or higher, effectively closing all descriptors except for the stdio +/// streams. +/// +/// The implementation of this function relies on `/dev/fd` being available +/// to provide the list of open fds. Any errors in enumerating or closing +/// the fds are silently ignored. +pub fn close_random_fds() { // FreeBSD, macOS and presumably other BSDish systems have /dev/fd as // a directory listing the current fd numbers for the process. // diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs index 86da96a60..5680cac0e 100644 --- a/wezterm/src/main.rs +++ b/wezterm/src/main.rs @@ -268,6 +268,7 @@ fn delegate_to_gui() -> anyhow::Result<()> { #[cfg(unix)] { use std::os::unix::process::CommandExt; + portable_pty::unix::close_random_fds(); return Err(anyhow::anyhow!("failed to exec: {:?}", cmd.exec())); }