mirror of
https://github.com/alacritty/alacritty.git
synced 2026-11-20 21:23:23 +03:00
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:
1 parent
889fa412c1
commit
96f488dd3f
10 files changed
+232
-78
No files matched your search
@@ -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.
|
||||
- Crash when OpenGL context resets
|
||||
- Crash when committing text with some IMEs on macOS
|
||||
- Signal termination skipping resource cleanup
|
||||
|
||||
## 0.16.1
|
||||
|
||||
|
||||
Generated
+4
-2
@@ -56,9 +56,11 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"png",
|
||||
"polling",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
"signal-hook",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"toml_edit 0.24.0+spec-1.1.0",
|
||||
@@ -1797,9 +1799,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.3.18"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
|
||||
checksum = "3b57709da74f9ff9f4a27dce9526eec25ca8407c45a7887243b031a58935fb8e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
|
||||
@@ -34,9 +34,11 @@ libc = "0.2"
|
||||
log = { version = "0.4", features = ["std", "serde"] }
|
||||
notify = "8.0.0"
|
||||
parking_lot = "0.12.0"
|
||||
polling = "3.11.0"
|
||||
serde_json = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_yaml = "0.9.25"
|
||||
signal-hook = { version = "0.4.3", default-features = false }
|
||||
tempfile = "3.12.0"
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
|
||||
@@ -58,10 +58,10 @@ use crate::display::hint::HintMatch;
|
||||
use crate::display::window::{ImeInhibitor, Window};
|
||||
use crate::display::{Display, Preedit, SizeInfo};
|
||||
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::message_bar::{Message, MessageBuffer};
|
||||
#[cfg(unix)]
|
||||
use crate::polling::ipc::{self, SocketReply};
|
||||
use crate::scheduler::{Scheduler, TimerId, Topic};
|
||||
use crate::window_context::WindowContext;
|
||||
|
||||
@@ -389,6 +389,9 @@ impl ApplicationHandler<Event> for Processor {
|
||||
error!("Could not open window: {err:?}");
|
||||
}
|
||||
},
|
||||
// Shutdown all windows.
|
||||
#[cfg(unix)]
|
||||
(EventType::Shutdown, _) => event_loop.exit(),
|
||||
// Process events affecting all windows.
|
||||
(payload, None) => {
|
||||
let event = WinitEvent::UserEvent(Event::new(payload, None));
|
||||
@@ -550,6 +553,8 @@ pub enum EventType {
|
||||
BlinkCursor,
|
||||
BlinkCursorTimeout,
|
||||
SearchNext,
|
||||
#[cfg(unix)]
|
||||
Shutdown,
|
||||
Frame,
|
||||
}
|
||||
|
||||
@@ -1924,7 +1929,7 @@ impl input::Processor<EventProxy, ActionContext<'_, Notifier, EventProxy>> {
|
||||
TerminalEvent::Exit | TerminalEvent::ChildExit(_) | TerminalEvent::Wakeup => (),
|
||||
},
|
||||
#[cfg(unix)]
|
||||
EventType::IpcConfig(_) | EventType::IpcGetConfig(..) => (),
|
||||
EventType::IpcConfig(_) | EventType::IpcGetConfig(..) | EventType::Shutdown => (),
|
||||
EventType::Message(_)
|
||||
| EventType::ConfigReload(_)
|
||||
| EventType::CreateWindow(_)
|
||||
|
||||
@@ -34,8 +34,6 @@ mod daemon;
|
||||
mod display;
|
||||
mod event;
|
||||
mod input;
|
||||
#[cfg(unix)]
|
||||
mod ipc;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
@@ -43,6 +41,8 @@ mod message_bar;
|
||||
mod migrate;
|
||||
#[cfg(windows)]
|
||||
mod panic;
|
||||
#[cfg(unix)]
|
||||
mod polling;
|
||||
mod renderer;
|
||||
mod scheduler;
|
||||
mod string;
|
||||
@@ -63,6 +63,8 @@ use crate::config::monitor::ConfigMonitor;
|
||||
use crate::event::{Event, Processor};
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::macos::locale;
|
||||
#[cfg(unix)]
|
||||
use crate::polling::{IoListener, ipc};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
#[cfg(windows)]
|
||||
@@ -114,7 +116,7 @@ impl Drop for TemporaryFiles {
|
||||
fn drop(&mut self) {
|
||||
// Clean up the IPC socket file.
|
||||
#[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);
|
||||
}
|
||||
|
||||
@@ -186,8 +188,8 @@ fn alacritty(mut options: Options) -> Result<(), Box<dyn Error>> {
|
||||
// Create the IPC socket listener.
|
||||
#[cfg(unix)]
|
||||
let socket_path = if config.ipc_socket() {
|
||||
match ipc::spawn_ipc_socket(&options, window_event_loop.create_proxy()) {
|
||||
Ok(path) => Some(path),
|
||||
match IoListener::spawn(&options, window_event_loop.create_proxy()) {
|
||||
Ok(handle) => Some(handle.ipc_socket_path),
|
||||
Err(err) if options.daemon => return Err(err.into()),
|
||||
Err(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::net::Shutdown;
|
||||
use std::os::unix::net::{UnixListener, UnixStream};
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::{env, fs, process};
|
||||
use std::{env, fs};
|
||||
|
||||
use log::{error, warn};
|
||||
use std::result::Result;
|
||||
use winit::event_loop::EventLoopProxy;
|
||||
use winit::window::WindowId;
|
||||
|
||||
use alacritty_terminal::thread;
|
||||
|
||||
use crate::cli::{Options, SocketMessage};
|
||||
use crate::event::{Event, EventType};
|
||||
|
||||
/// Environment variable name for the IPC socket path.
|
||||
const ALACRITTY_SOCKET_ENV: &str = "ALACRITTY_SOCKET";
|
||||
|
||||
/// Create an IPC socket.
|
||||
pub fn spawn_ipc_socket(
|
||||
options: &Options,
|
||||
/// IPC socket listener.
|
||||
pub struct IpcListener {
|
||||
pub socket: UnixListener,
|
||||
|
||||
event_proxy: EventLoopProxy<Event>,
|
||||
) -> IoResult<PathBuf> {
|
||||
// Create the IPC socket and export its path as env.
|
||||
data: String,
|
||||
}
|
||||
|
||||
let socket_path = options.socket.clone().unwrap_or_else(|| {
|
||||
let mut path = socket_dir();
|
||||
path.push(format!("{}-{}.sock", socket_prefix(), process::id()));
|
||||
path
|
||||
});
|
||||
impl IpcListener {
|
||||
pub fn new(
|
||||
options: &Options,
|
||||
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()) };
|
||||
if options.daemon {
|
||||
println!("ALACRITTY_SOCKET={}; export ALACRITTY_SOCKET", socket_path.display());
|
||||
Ok(Self { event_proxy, socket, data: Default::default() })
|
||||
}
|
||||
|
||||
// Spawn a thread to listen on the IPC socket.
|
||||
thread::spawn_named("socket listener", move || {
|
||||
let mut data = String::new();
|
||||
for stream in listener.incoming().filter_map(Result::ok) {
|
||||
data.clear();
|
||||
let mut reader = BufReader::new(&stream);
|
||||
/// Process the next IPC message.
|
||||
pub fn process_message(&mut self) -> Result<(), IoError> {
|
||||
let (stream, _) = self.socket.accept()?;
|
||||
|
||||
match reader.read_line(&mut data) {
|
||||
Ok(0) | Err(_) => continue,
|
||||
Ok(_) => (),
|
||||
};
|
||||
self.data.clear();
|
||||
let mut reader = BufReader::new(&stream);
|
||||
|
||||
// Read pending events on socket.
|
||||
let message: SocketMessage = match serde_json::from_str(&data) {
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
warn!("Failed to convert data from socket: {err}");
|
||||
continue;
|
||||
},
|
||||
};
|
||||
match reader.read_line(&mut self.data) {
|
||||
Ok(0) | Err(_) => return Ok(()),
|
||||
Ok(_) => (),
|
||||
};
|
||||
|
||||
// Handle IPC events.
|
||||
match message {
|
||||
SocketMessage::CreateWindow(options) => {
|
||||
let event = Event::new(EventType::CreateWindow(options), None);
|
||||
let _ = event_proxy.send_event(event);
|
||||
},
|
||||
SocketMessage::Config(ipc_config) => {
|
||||
let window_id = ipc_config
|
||||
.window_id
|
||||
.and_then(|id| u64::try_from(id).ok())
|
||||
.map(WindowId::from);
|
||||
let event = Event::new(EventType::IpcConfig(ipc_config), window_id);
|
||||
let _ = 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 _ = event_proxy.send_event(event);
|
||||
},
|
||||
}
|
||||
let message: SocketMessage = match serde_json::from_str(&self.data) {
|
||||
Ok(message) => message,
|
||||
Err(err) => {
|
||||
warn!("Failed to parse IPC message: {err}");
|
||||
return Ok(());
|
||||
},
|
||||
};
|
||||
|
||||
// Handle IPC events.
|
||||
match message {
|
||||
SocketMessage::CreateWindow(options) => {
|
||||
let event = Event::new(EventType::CreateWindow(options), None);
|
||||
let _ = self.event_proxy.send_event(event);
|
||||
},
|
||||
SocketMessage::Config(ipc_config) => {
|
||||
let window_id =
|
||||
ipc_config.window_id.and_then(|id| u64::try_from(id).ok()).map(WindowId::from);
|
||||
let event = Event::new(EventType::IpcConfig(ipc_config), window_id);
|
||||
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.
|
||||
@@ -150,7 +151,7 @@ fn send_reply_fallible(stream: &mut UnixStream, message: SocketReply) -> IoResul
|
||||
|
||||
/// Directory for the IPC socket file.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn socket_dir() -> PathBuf {
|
||||
pub fn socket_dir() -> PathBuf {
|
||||
xdg::BaseDirectories::with_prefix("alacritty")
|
||||
.get_runtime_directory()
|
||||
.map(ToOwned::to_owned)
|
||||
@@ -161,7 +162,7 @@ fn socket_dir() -> PathBuf {
|
||||
|
||||
/// Directory for the IPC socket file.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn socket_dir() -> PathBuf {
|
||||
pub fn socket_dir() -> PathBuf {
|
||||
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
|
||||
/// display servers running for the same user.
|
||||
#[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();
|
||||
format!("Alacritty-{}", display.replace('/', "-"))
|
||||
}
|
||||
|
||||
/// File prefix matching all available sockets.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn socket_prefix() -> String {
|
||||
pub fn socket_prefix() -> String {
|
||||
String::from("Alacritty")
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ serde = { version = "1", features = ["derive", "rc"], optional = true }
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix-openpty = "0.2.0"
|
||||
rustix = { version = "1.0.0", default-features = false, features = ["std"] }
|
||||
signal-hook = "0.3.10"
|
||||
signal-hook = "0.4.3"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
piper = "0.2.1"
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::thread::JoinHandle;
|
||||
use std::time::Instant;
|
||||
|
||||
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::sync::FairMutex;
|
||||
@@ -44,7 +44,7 @@ pub enum Msg {
|
||||
/// Handles all the PTY I/O and runs the PTY parser which updates terminal
|
||||
/// state.
|
||||
pub struct EventLoop<T: tty::EventedPty, U: EventListener> {
|
||||
poll: Arc<polling::Poller>,
|
||||
poll: Arc<Poller>,
|
||||
pty: T,
|
||||
rx: PeekableReceiver<Msg>,
|
||||
tx: Sender<Msg>,
|
||||
@@ -68,7 +68,7 @@ where
|
||||
ref_test: bool,
|
||||
) -> io::Result<EventLoop<T, U>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let poll = polling::Poller::new()?.into();
|
||||
let poll = Poller::new()?.into();
|
||||
Ok(EventLoop {
|
||||
poll,
|
||||
pty,
|
||||
@@ -383,7 +383,7 @@ impl std::error::Error for EventLoopSendError {
|
||||
#[derive(Clone)]
|
||||
pub struct EventLoopSender {
|
||||
sender: Sender<Msg>,
|
||||
poller: Arc<polling::Poller>,
|
||||
poller: Arc<Poller>,
|
||||
}
|
||||
|
||||
impl EventLoopSender {
|
||||
|
||||
Reference in new issue
Block a user