|
| 1 | +/// Ensure inherited standard streams use the blocking semantics expected by |
| 2 | +/// Rust's standard library and by the tools embedded in Vite+. |
| 3 | +/// |
| 4 | +/// Node.js marks non-TTY stdio as non-blocking, and child processes inherit |
| 5 | +/// that flag through the shared open file description. Clear `O_NONBLOCK` |
| 6 | +/// once at process entry so unowned writers do not panic or truncate output |
| 7 | +/// when a consumer applies backpressure. |
| 8 | +#[cfg(unix)] |
| 9 | +pub fn ensure_blocking_stdio() { |
| 10 | + use std::{io, os::fd::AsFd}; |
| 11 | + |
| 12 | + let stdin = io::stdin(); |
| 13 | + let stdout = io::stdout(); |
| 14 | + let stderr = io::stderr(); |
| 15 | + |
| 16 | + for fd in [stdin.as_fd(), stdout.as_fd(), stderr.as_fd()] { |
| 17 | + ensure_blocking_fd(fd); |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +#[cfg(unix)] |
| 22 | +fn ensure_blocking_fd(fd: std::os::fd::BorrowedFd<'_>) { |
| 23 | + use nix::{ |
| 24 | + fcntl::{FcntlArg, OFlag, fcntl}, |
| 25 | + unistd::isatty, |
| 26 | + }; |
| 27 | + |
| 28 | + if isatty(fd).unwrap_or(false) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + let Ok(flags) = fcntl(fd, FcntlArg::F_GETFL) else { |
| 33 | + return; |
| 34 | + }; |
| 35 | + let flags = OFlag::from_bits_retain(flags); |
| 36 | + if flags.contains(OFlag::O_NONBLOCK) { |
| 37 | + let _ = fcntl(fd, FcntlArg::F_SETFL(flags.difference(OFlag::O_NONBLOCK))); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +#[cfg(not(unix))] |
| 42 | +pub fn ensure_blocking_stdio() {} |
| 43 | + |
| 44 | +#[cfg(all(test, unix))] |
| 45 | +mod tests { |
| 46 | + use std::os::{fd::AsFd, unix::net::UnixStream}; |
| 47 | + |
| 48 | + use nix::fcntl::{FcntlArg, OFlag, fcntl}; |
| 49 | + |
| 50 | + use super::ensure_blocking_fd; |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn clears_nonblocking_from_a_non_tty_file_description() { |
| 54 | + let (stream, _peer) = UnixStream::pair().unwrap(); |
| 55 | + stream.set_nonblocking(true).unwrap(); |
| 56 | + |
| 57 | + ensure_blocking_fd(stream.as_fd()); |
| 58 | + |
| 59 | + let flags = fcntl(&stream, FcntlArg::F_GETFL).unwrap(); |
| 60 | + assert!(!OFlag::from_bits_retain(flags).contains(OFlag::O_NONBLOCK)); |
| 61 | + } |
| 62 | +} |
0 commit comments