Fix resource cleanup for signal shutdown

This fixes an issue where Alacritty's resources, like its socket, would
stick around after getting killed, since termination signals like
SIGTERM were not handled explicitly.

To handle these signals, the IPC thread was changed to a general-purpose
I/O polling thread, listening for events on a signal pipe and the IPC
socket.

While this does not provide support for Windows, we also do not have an
IPC socket on Windows we would need to clean up.

Closes #8805.
This commit is contained in:
Christian Duerr authored and GitHub committed 2026-03-05 05:14:21 +00:00
1 parent 889fa412c1
commit 96f488dd3f
10 files changed
+232 -78

No files matched your search

+1
View File
@@ -35,6 +35,7 @@ Notable changes to the `alacritty_terminal` crate are documented in its
- Subprocesses on OpenBSD now run with their CWD set to that of the shell's foreground process. - Subprocesses on OpenBSD now run with their CWD set to that of the shell's foreground process.
- Crash when OpenGL context resets - Crash when OpenGL context resets
- Crash when committing text with some IMEs on macOS - Crash when committing text with some IMEs on macOS
- Signal termination skipping resource cleanup
## 0.16.1 ## 0.16.1
Generated
+4 -2
View File
@@ -56,9 +56,11 @@ dependencies = [
"objc2-foundation 0.3.2", "objc2-foundation 0.3.2",
"parking_lot", "parking_lot",
"png", "png",
"polling",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
"signal-hook",
"tempfile", "tempfile",
"toml", "toml",
"toml_edit 0.24.0+spec-1.1.0", "toml_edit 0.24.0+spec-1.1.0",
@@ -1797,9 +1799,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "signal-hook" name = "signal-hook"
version = "0.3.18" version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" checksum = "3b57709da74f9ff9f4a27dce9526eec25ca8407c45a7887243b031a58935fb8e"
dependencies = [ dependencies = [
"libc", "libc",
"signal-hook-registry", "signal-hook-registry",
+2
View File
@@ -34,9 +34,11 @@ libc = "0.2"
log = { version = "0.4", features = ["std", "serde"] } log = { version = "0.4", features = ["std", "serde"] }
notify = "8.0.0" notify = "8.0.0"
parking_lot = "0.12.0" parking_lot = "0.12.0"
polling = "3.11.0"
serde_json = "1" serde_json = "1"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_yaml = "0.9.25" serde_yaml = "0.9.25"
signal-hook = { version = "0.4.3", default-features = false }
tempfile = "3.12.0" tempfile = "3.12.0"
toml.workspace = true toml.workspace = true
toml_edit.workspace = true toml_edit.workspace = true
+8 -3
View File
@@ -58,10 +58,10 @@ use crate::display::hint::HintMatch;
use crate::display::window::{ImeInhibitor, Window}; use crate::display::window::{ImeInhibitor, Window};
use crate::display::{Display, Preedit, SizeInfo}; use crate::display::{Display, Preedit, SizeInfo};
use crate::input::{self, ActionContext as _, FONT_SIZE_STEP}; use crate::input::{self, ActionContext as _, FONT_SIZE_STEP};
#[cfg(unix)]
use crate::ipc::{self, SocketReply};
use crate::logging::{LOG_TARGET_CONFIG, LOG_TARGET_WINIT}; use crate::logging::{LOG_TARGET_CONFIG, LOG_TARGET_WINIT};
use crate::message_bar::{Message, MessageBuffer}; use crate::message_bar::{Message, MessageBuffer};
#[cfg(unix)]
use crate::polling::ipc::{self, SocketReply};
use crate::scheduler::{Scheduler, TimerId, Topic}; use crate::scheduler::{Scheduler, TimerId, Topic};
use crate::window_context::WindowContext; use crate::window_context::WindowContext;
@@ -389,6 +389,9 @@ impl ApplicationHandler<Event> for Processor {
error!("Could not open window: {err:?}"); error!("Could not open window: {err:?}");
} }
}, },
// Shutdown all windows.
#[cfg(unix)]
(EventType::Shutdown, _) => event_loop.exit(),
// Process events affecting all windows. // Process events affecting all windows.
(payload, None) => { (payload, None) => {
let event = WinitEvent::UserEvent(Event::new(payload, None)); let event = WinitEvent::UserEvent(Event::new(payload, None));
@@ -550,6 +553,8 @@ pub enum EventType {
BlinkCursor, BlinkCursor,
BlinkCursorTimeout, BlinkCursorTimeout,
SearchNext, SearchNext,
#[cfg(unix)]
Shutdown,
Frame, Frame,
} }
@@ -1924,7 +1929,7 @@ impl input::Processor<EventProxy, ActionContext<'_, Notifier, EventProxy>> {
TerminalEvent::Exit | TerminalEvent::ChildExit(_) | TerminalEvent::Wakeup => (), TerminalEvent::Exit | TerminalEvent::ChildExit(_) | TerminalEvent::Wakeup => (),
}, },
#[cfg(unix)] #[cfg(unix)]
EventType::IpcConfig(_) | EventType::IpcGetConfig(..) => (), EventType::IpcConfig(_) | EventType::IpcGetConfig(..) | EventType::Shutdown => (),
EventType::Message(_) EventType::Message(_)
| EventType::ConfigReload(_) | EventType::ConfigReload(_)
| EventType::CreateWindow(_) | EventType::CreateWindow(_)
+7 -5
View File
@@ -34,8 +34,6 @@ mod daemon;
mod display; mod display;
mod event; mod event;
mod input; mod input;
#[cfg(unix)]
mod ipc;
mod logging; mod logging;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
mod macos; mod macos;
@@ -43,6 +41,8 @@ mod message_bar;
mod migrate; mod migrate;
#[cfg(windows)] #[cfg(windows)]
mod panic; mod panic;
#[cfg(unix)]
mod polling;
mod renderer; mod renderer;
mod scheduler; mod scheduler;
mod string; mod string;
@@ -63,6 +63,8 @@ use crate::config::monitor::ConfigMonitor;
use crate::event::{Event, Processor}; use crate::event::{Event, Processor};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use crate::macos::locale; use crate::macos::locale;
#[cfg(unix)]
use crate::polling::{IoListener, ipc};
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
#[cfg(windows)] #[cfg(windows)]
@@ -114,7 +116,7 @@ impl Drop for TemporaryFiles {
fn drop(&mut self) { fn drop(&mut self) {
// Clean up the IPC socket file. // Clean up the IPC socket file.
#[cfg(unix)] #[cfg(unix)]
if let Some(socket_path) = &self.socket_path { if let Some(socket_path) = self.socket_path.as_deref() {
let _ = fs::remove_file(socket_path); let _ = fs::remove_file(socket_path);
} }
@@ -186,8 +188,8 @@ fn alacritty(mut options: Options) -> Result<(), Box<dyn Error>> {
// Create the IPC socket listener. // Create the IPC socket listener.
#[cfg(unix)] #[cfg(unix)]
let socket_path = if config.ipc_socket() { let socket_path = if config.ipc_socket() {
match ipc::spawn_ipc_socket(&options, window_event_loop.create_proxy()) { match IoListener::spawn(&options, window_event_loop.create_proxy()) {
Ok(path) => Some(path), Ok(handle) => Some(handle.ipc_socket_path),
Err(err) if options.daemon => return Err(err.into()), Err(err) if options.daemon => return Err(err.into()),
Err(err) => { Err(err) => {
log::warn!("Unable to create socket: {err:?}"); log::warn!("Unable to create socket: {err:?}");
@@ -5,89 +5,90 @@ use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write}; use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write};
use std::net::Shutdown; use std::net::Shutdown;
use std::os::unix::net::{UnixListener, UnixStream}; use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::{env, fs, process}; use std::{env, fs};
use log::{error, warn}; use log::{error, warn};
use std::result::Result; use std::result::Result;
use winit::event_loop::EventLoopProxy; use winit::event_loop::EventLoopProxy;
use winit::window::WindowId; use winit::window::WindowId;
use alacritty_terminal::thread;
use crate::cli::{Options, SocketMessage}; use crate::cli::{Options, SocketMessage};
use crate::event::{Event, EventType}; use crate::event::{Event, EventType};
/// Environment variable name for the IPC socket path. /// Environment variable name for the IPC socket path.
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET"; const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
/// Create an IPC socket. /// IPC socket listener.
pub fn spawn_ipc_socket( pub struct IpcListener {
options: &Options, pub socket: UnixListener,
event_proxy: EventLoopProxy<Event>, event_proxy: EventLoopProxy<Event>,
) -> IoResult<PathBuf> { data: String,
// Create the IPC socket and export its path as env. }
let socket_path = options.socket.clone().unwrap_or_else(|| { impl IpcListener {
let mut path = socket_dir(); pub fn new(
path.push(format!("{}-{}.sock", socket_prefix(), process::id())); options: &Options,
path event_proxy: EventLoopProxy<Event>,
}); path: &Path,
) -> Result<Self, IoError> {
// Create unix socket in nonblocking mode.
let socket = UnixListener::bind(path)?;
socket.set_nonblocking(true)?;
let listener = UnixListener::bind(&socket_path)?; // Register socket path as environment variable for `alacritty msg`.
unsafe { env::set_var(ALACRITTY_SOCKET_ENV, path.as_os_str()) };
if options.daemon {
println!("ALACRITTY_SOCKET={}; export ALACRITTY_SOCKET", path.display());
}
unsafe { env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str()) }; Ok(Self { event_proxy, socket, data: Default::default() })
if options.daemon {
println!("ALACRITTY_SOCKET={}; export ALACRITTY_SOCKET", socket_path.display());
} }
// Spawn a thread to listen on the IPC socket. /// Process the next IPC message.
thread::spawn_named("socket listener", move || { pub fn process_message(&mut self) -> Result<(), IoError> {
let mut data = String::new(); let (stream, _) = self.socket.accept()?;
for stream in listener.incoming().filter_map(Result::ok) {
data.clear();
let mut reader = BufReader::new(&stream);
match reader.read_line(&mut data) { self.data.clear();
Ok(0) | Err(_) => continue, let mut reader = BufReader::new(&stream);
Ok(_) => (),
};
// Read pending events on socket. match reader.read_line(&mut self.data) {
let message: SocketMessage = match serde_json::from_str(&data) { Ok(0) | Err(_) => return Ok(()),
Ok(message) => message, Ok(_) => (),
Err(err) => { };
warn!("Failed to convert data from socket: {err}");
continue;
},
};
// Handle IPC events. let message: SocketMessage = match serde_json::from_str(&self.data) {
match message { Ok(message) => message,
SocketMessage::CreateWindow(options) => { Err(err) => {
let event = Event::new(EventType::CreateWindow(options), None); warn!("Failed to parse IPC message: {err}");
let _ = event_proxy.send_event(event); return Ok(());
}, },
SocketMessage::Config(ipc_config) => { };
let window_id = ipc_config
.window_id // Handle IPC events.
.and_then(|id| u64::try_from(id).ok()) match message {
.map(WindowId::from); SocketMessage::CreateWindow(options) => {
let event = Event::new(EventType::IpcConfig(ipc_config), window_id); let event = Event::new(EventType::CreateWindow(options), None);
let _ = event_proxy.send_event(event); let _ = self.event_proxy.send_event(event);
}, },
SocketMessage::GetConfig(config) => { SocketMessage::Config(ipc_config) => {
let window_id = let window_id =
config.window_id.and_then(|id| u64::try_from(id).ok()).map(WindowId::from); ipc_config.window_id.and_then(|id| u64::try_from(id).ok()).map(WindowId::from);
let event = Event::new(EventType::IpcGetConfig(Arc::new(stream)), window_id); let event = Event::new(EventType::IpcConfig(ipc_config), window_id);
let _ = event_proxy.send_event(event); let _ = self.event_proxy.send_event(event);
}, },
} SocketMessage::GetConfig(config) => {
let window_id =
config.window_id.and_then(|id| u64::try_from(id).ok()).map(WindowId::from);
let event = Event::new(EventType::IpcGetConfig(Arc::new(stream)), window_id);
let _ = self.event_proxy.send_event(event);
},
} }
});
Ok(socket_path) Ok(())
}
} }
/// Send a message to the active Alacritty socket. /// Send a message to the active Alacritty socket.
@@ -150,7 +151,7 @@ fn send_reply_fallible(stream: &mut UnixStream, message: SocketReply) -> IoResul
/// Directory for the IPC socket file. /// Directory for the IPC socket file.
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
fn socket_dir() -> PathBuf { pub fn socket_dir() -> PathBuf {
xdg::BaseDirectories::with_prefix("alacritty") xdg::BaseDirectories::with_prefix("alacritty")
.get_runtime_directory() .get_runtime_directory()
.map(ToOwned::to_owned) .map(ToOwned::to_owned)
@@ -161,7 +162,7 @@ fn socket_dir() -> PathBuf {
/// Directory for the IPC socket file. /// Directory for the IPC socket file.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn socket_dir() -> PathBuf { pub fn socket_dir() -> PathBuf {
env::temp_dir() env::temp_dir()
} }
@@ -219,14 +220,14 @@ fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> {
/// This prefix will include display server information to allow for environments with multiple /// This prefix will include display server information to allow for environments with multiple
/// display servers running for the same user. /// display servers running for the same user.
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
fn socket_prefix() -> String { pub fn socket_prefix() -> String {
let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default(); let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default();
format!("Alacritty-{}", display.replace('/', "-")) format!("Alacritty-{}", display.replace('/', "-"))
} }
/// File prefix matching all available sockets. /// File prefix matching all available sockets.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn socket_prefix() -> String { pub fn socket_prefix() -> String {
String::from("Alacritty") String::from("Alacritty")
} }
+109
View File
@@ -0,0 +1,109 @@
//! Unix I/O event polling.
use polling::{Event as PollEvent, Events, Poller};
use std::io::Error as IoError;
use std::path::PathBuf;
use std::process;
use log::error;
use std::result::Result;
use winit::event_loop::EventLoopProxy;
use alacritty_terminal::thread;
use crate::cli::Options;
use crate::event::Event;
use crate::polling::ipc::IpcListener;
use crate::polling::signal::SignalListener;
pub mod ipc;
mod signal;
/// Polling key for signal read events.
const SIGNAL_READ_KEY: usize = 1;
/// Polling key for IPC read events.
const IPC_READ_KEY: usize = 0;
/// Unix I/O event listener.
pub struct IoListener {
signal_listener: SignalListener,
ipc_listener: IpcListener,
events: Events,
poller: Poller,
}
impl IoListener {
/// Create background thread to listen for I/O events.
pub fn spawn(
options: &Options,
event_proxy: EventLoopProxy<Event>,
) -> Result<IoListenerHandle, IoError> {
let poller = Poller::new()?;
let events = Events::new();
// Create socket listener for IPC messages.
let ipc_socket_path = options.socket.clone().unwrap_or_else(|| {
let mut path = ipc::socket_dir();
path.push(format!("{}-{}.sock", ipc::socket_prefix(), process::id()));
path
});
let ipc_listener = IpcListener::new(options, event_proxy.clone(), &ipc_socket_path)?;
// Create listener for Unix signals.
let signal_listener = SignalListener::new(event_proxy)?;
// SAFETY: Correct drop order is taken care of by `Drop` implementation.
unsafe { poller.add(&signal_listener.pipe, PollEvent::readable(SIGNAL_READ_KEY))? };
unsafe { poller.add(&ipc_listener.socket, PollEvent::readable(IPC_READ_KEY))? };
let mut listener = Self { signal_listener, ipc_listener, events, poller };
thread::spawn_named("io event listener", move || {
loop {
if let Err(err) = listener.poll() {
error!("Failed to poll for I/O events: {err}");
}
}
});
Ok(IoListenerHandle { ipc_socket_path })
}
/// Process the next I/O event.
fn poll(&mut self) -> Result<(), IoError> {
// Ensure interests are present for the next poll.
self.poller.modify(&self.signal_listener.pipe, PollEvent::readable(SIGNAL_READ_KEY))?;
self.poller.modify(&self.ipc_listener.socket, PollEvent::readable(IPC_READ_KEY))?;
// Wait for the next event to be ready.
self.events.clear();
self.poller.wait(&mut self.events, None)?;
for event in self.events.iter() {
if event.key == IPC_READ_KEY {
self.ipc_listener.process_message()?;
} else if event.key == SIGNAL_READ_KEY {
self.signal_listener.process_signal()?;
}
}
Ok(())
}
}
impl Drop for IoListener {
fn drop(&mut self) {
if let Err(err) = self.poller.delete(&self.signal_listener.pipe) {
error!("Failed to remove signal listener interest: {err}");
}
if let Err(err) = self.poller.delete(&self.ipc_listener.socket) {
error!("Failed to remove IPC listener interest: {err}");
}
}
}
/// Public I/O event listener state.
pub struct IoListenerHandle {
pub ipc_socket_path: PathBuf,
}
+32
View File
@@ -0,0 +1,32 @@
//! Unix signal listener.
use std::io::Error as IoError;
use std::os::unix::net::UnixStream;
use signal_hook::consts::{SIGINT, SIGTERM};
use signal_hook::low_level::pipe;
use winit::event_loop::EventLoopProxy;
use crate::event::{Event, EventType};
pub struct SignalListener {
pub pipe: UnixStream,
event_proxy: EventLoopProxy<Event>,
}
impl SignalListener {
pub fn new(event_proxy: EventLoopProxy<Event>) -> Result<Self, IoError> {
let (pipe, write) = UnixStream::pair()?;
pipe::register(SIGINT, write.try_clone()?)?;
pipe::register(SIGTERM, write)?;
Ok(Self { event_proxy, pipe })
}
/// Process the next signal.
pub fn process_signal(&mut self) -> Result<(), IoError> {
let event = Event::new(EventType::Shutdown, None);
let _ = self.event_proxy.send_event(event);
Ok(())
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ serde = { version = "1", features = ["derive", "rc"], optional = true }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
rustix-openpty = "0.2.0" rustix-openpty = "0.2.0"
rustix = { version = "1.0.0", default-features = false, features = ["std"] } rustix = { version = "1.0.0", default-features = false, features = ["std"] }
signal-hook = "0.3.10" signal-hook = "0.4.3"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
piper = "0.2.1" piper = "0.2.1"
+4 -4
View File
@@ -12,7 +12,7 @@ use std::thread::JoinHandle;
use std::time::Instant; use std::time::Instant;
use log::error; use log::error;
use polling::{Event as PollingEvent, Events, PollMode}; use polling::{Event as PollingEvent, Events, PollMode, Poller};
use crate::event::{self, Event, EventListener, WindowSize}; use crate::event::{self, Event, EventListener, WindowSize};
use crate::sync::FairMutex; use crate::sync::FairMutex;
@@ -44,7 +44,7 @@ pub enum Msg {
/// Handles all the PTY I/O and runs the PTY parser which updates terminal /// Handles all the PTY I/O and runs the PTY parser which updates terminal
/// state. /// state.
pub struct EventLoop<T: tty::EventedPty, U: EventListener> { pub struct EventLoop<T: tty::EventedPty, U: EventListener> {
poll: Arc<polling::Poller>, poll: Arc<Poller>,
pty: T, pty: T,
rx: PeekableReceiver<Msg>, rx: PeekableReceiver<Msg>,
tx: Sender<Msg>, tx: Sender<Msg>,
@@ -68,7 +68,7 @@ where
ref_test: bool, ref_test: bool,
) -> io::Result<EventLoop<T, U>> { ) -> io::Result<EventLoop<T, U>> {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
let poll = polling::Poller::new()?.into(); let poll = Poller::new()?.into();
Ok(EventLoop { Ok(EventLoop {
poll, poll,
pty, pty,
@@ -383,7 +383,7 @@ impl std::error::Error for EventLoopSendError {
#[derive(Clone)] #[derive(Clone)]
pub struct EventLoopSender { pub struct EventLoopSender {
sender: Sender<Msg>, sender: Sender<Msg>,
poller: Arc<polling::Poller>, poller: Arc<Poller>,
} }
impl EventLoopSender { impl EventLoopSender {