Skip to content

Commit c1ea96a

Browse files
authored
fix(cli): avoid blocking dev app exit handling on the stderr reader (#16110)
1 parent d5bd046 commit c1ea96a

3 files changed

Lines changed: 60 additions & 42 deletions

File tree

‎.changes/cli-dev-stderr-hang.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"tauri-cli": patch:bug
3+
"@tauri-apps/cli": patch:bug
4+
---
5+
6+
Fix `tauri dev` not reacting to the app exiting when a process spawned by the app kept its stderr open, and stop keeping the whole app stderr output in memory. Also fix command output capture that could return empty output when the command finished before its output was read.

‎crates/tauri-cli/src/interface/rust/desktop.rs‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use std::{
1818
Arc, Mutex,
1919
atomic::{AtomicBool, Ordering},
2020
},
21+
time::Duration,
2122
};
2223
use tauri_utils::platform::Target as TargetPlatform;
2324

@@ -99,19 +100,22 @@ pub fn run_dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
99100
let dev_child = Arc::new(dev_child);
100101
let dev_child_stderr = dev_child.take_stderr().unwrap();
101102
let mut stderr = BufReader::new(dev_child_stderr);
102-
let stderr_lines = Arc::new(Mutex::new(Vec::new()));
103-
let stderr_lines_ = stderr_lines.clone();
103+
// only the last line is needed to detect cargo compilation errors
104+
let last_stderr_line = Arc::new(Mutex::new(None::<String>));
105+
let last_stderr_line_ = last_stderr_line.clone();
106+
// dropped when the reader thread finishes
107+
let (stderr_done_tx, stderr_done_rx) = std::sync::mpsc::channel::<()>();
104108
std::thread::spawn(move || {
109+
let _stderr_done_tx = stderr_done_tx;
105110
let mut buf = Vec::new();
106-
let mut lines = stderr_lines_.lock().unwrap();
107111
let mut io_stderr = std::io::stderr();
108112
loop {
109113
buf.clear();
110114
if let Ok(0) = tauri_utils::io::read_line(&mut stderr, &mut buf) {
111115
break;
112116
}
113117
let _ = io_stderr.write_all(&buf);
114-
lines.push(String::from_utf8_lossy(&buf).into_owned());
118+
*last_stderr_line_.lock().unwrap() = Some(String::from_utf8_lossy(&buf).into_owned());
115119
}
116120
});
117121
let dev_child_ = dev_child.clone();
@@ -121,13 +125,15 @@ pub fn run_dev<F: Fn(Option<i32>, ExitReason) + Send + Sync + 'static>(
121125
if status.success() {
122126
on_exit(status.code(), ExitReason::NormalExit);
123127
} else {
124-
let is_cargo_compile_error = stderr_lines
128+
// give the reader a moment to consume the remaining output,
129+
// without blocking forever if a grandchild process keeps stderr open
130+
let _ = stderr_done_rx.recv_timeout(Duration::from_secs(1));
131+
let is_cargo_compile_error = last_stderr_line
125132
.lock()
126133
.unwrap()
127-
.last()
134+
.take()
128135
.map(|l| l.contains("could not compile"))
129136
.unwrap_or_default();
130-
stderr_lines.lock().unwrap().clear();
131137

132138
on_exit(
133139
status.code(),

‎crates/tauri-cli/src/lib.rs‎

Lines changed: 41 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,7 @@ use serde::{Deserialize, Serialize};
3838
use std::io::{BufReader, Write};
3939
use std::process::{Command, ExitStatus, Output, Stdio, exit};
4040
use std::{
41-
ffi::OsString,
42-
fmt::Display,
43-
fs::read_to_string,
44-
io::BufRead,
45-
path::PathBuf,
46-
str::FromStr,
47-
sync::{Arc, Mutex},
41+
ffi::OsString, fmt::Display, fs::read_to_string, io::BufRead, path::PathBuf, str::FromStr,
4842
};
4943

5044
use crate::error::Context;
@@ -365,53 +359,50 @@ impl CommandExt for Command {
365359
.with_context(|| format!("failed to run command `{cmdline}`"))?;
366360

367361
let mut stdout = child.stdout.take().map(BufReader::new).unwrap();
368-
let stdout_lines = Arc::new(Mutex::new(Vec::new()));
369-
let stdout_lines_ = stdout_lines.clone();
370-
std::thread::spawn(move || {
362+
let stdout_thread = std::thread::spawn(move || {
371363
let mut line = String::new();
372-
if let Ok(mut lines) = stdout_lines_.lock() {
373-
loop {
374-
line.clear();
375-
match stdout.read_line(&mut line) {
376-
Ok(0) => break,
377-
Ok(_) => {
378-
log::debug!(action = "stdout"; "{}", line.trim_end());
379-
lines.extend(line.as_bytes());
380-
}
381-
Err(_) => (),
364+
let mut lines = Vec::new();
365+
loop {
366+
line.clear();
367+
match stdout.read_line(&mut line) {
368+
Ok(0) => break,
369+
Ok(_) => {
370+
log::debug!(action = "stdout"; "{}", line.trim_end());
371+
lines.extend(line.as_bytes());
382372
}
373+
Err(_) => (),
383374
}
384375
}
376+
lines
385377
});
386378

387379
let mut stderr = child.stderr.take().map(BufReader::new).unwrap();
388-
let stderr_lines = Arc::new(Mutex::new(Vec::new()));
389-
let stderr_lines_ = stderr_lines.clone();
390-
std::thread::spawn(move || {
380+
let stderr_thread = std::thread::spawn(move || {
391381
let mut line = String::new();
392-
if let Ok(mut lines) = stderr_lines_.lock() {
393-
loop {
394-
line.clear();
395-
match stderr.read_line(&mut line) {
396-
Ok(0) => break,
397-
Ok(_) => {
398-
log::debug!(action = "stderr"; "{}", line.trim_end());
399-
lines.extend(line.as_bytes());
400-
}
401-
Err(_) => (),
382+
let mut lines = Vec::new();
383+
loop {
384+
line.clear();
385+
match stderr.read_line(&mut line) {
386+
Ok(0) => break,
387+
Ok(_) => {
388+
log::debug!(action = "stderr"; "{}", line.trim_end());
389+
lines.extend(line.as_bytes());
402390
}
391+
Err(_) => (),
403392
}
404393
}
394+
lines
405395
});
406396

407397
let status = child
408398
.wait()
409399
.with_context(|| format!("failed to run command `{cmdline}`"))?;
410400

401+
// wait for the readers to reach EOF so the output is complete
411402
let output = Output {
412403
status,
413-
stdout: std::mem::take(&mut *stdout_lines.lock().unwrap()),
414-
stderr: std::mem::take(&mut *stderr_lines.lock().unwrap()),
404+
stdout: stdout_thread.join().unwrap_or_default(),
405+
stderr: stderr_thread.join().unwrap_or_default(),
415406
};
416407

417408
if output.status.success() {
@@ -441,4 +432,19 @@ mod tests {
441432
let help = Cli::command().render_help().to_string();
442433
assert!(help.contains("Build"));
443434
}
435+
436+
#[cfg(unix)]
437+
#[test]
438+
fn output_ok_captures_all_output() {
439+
use crate::CommandExt;
440+
441+
for _ in 0..20 {
442+
let output = std::process::Command::new("sh")
443+
.args(["-c", "echo out1; echo err1 >&2; echo out2; echo err2 >&2"])
444+
.output_ok()
445+
.unwrap();
446+
assert_eq!(output.stdout, b"out1\nout2\n");
447+
assert_eq!(output.stderr, b"err1\nerr2\n");
448+
}
449+
}
444450
}

0 commit comments

Comments
 (0)