Skip to content

Commit 5651daf

Browse files
committed
Fix Fd::as_raw_fd_or_null_fd: set pased fd to be blocking
Signed-off-by: Jiahao XU <[email protected]>
1 parent db04a66 commit 5651daf

File tree

1 file changed

+36
-12
lines changed

1 file changed

+36
-12
lines changed

src/native_mux_impl/stdio.rs

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
1-
use crate::stdio::StdioImpl;
2-
use crate::Error;
3-
use crate::Stdio;
1+
use crate::{stdio::StdioImpl, Error, Stdio};
42

5-
use once_cell::sync::OnceCell;
3+
use std::{
4+
fs::{File, OpenOptions},
5+
io,
6+
os::unix::io::{AsRawFd, RawFd},
7+
};
68

7-
use std::fs::{File, OpenOptions};
8-
use std::io;
9-
use std::os::unix::io::{AsRawFd, RawFd};
9+
use libc::{c_int, fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
10+
use once_cell::sync::OnceCell;
1011
use tokio_pipe::{pipe, PipeRead, PipeWrite};
1112

1213
fn create_pipe() -> Result<(PipeRead, PipeWrite), Error> {
@@ -35,16 +36,39 @@ pub(crate) enum Fd {
3536
Null,
3637
}
3738

39+
fn cvt(ret: c_int) -> io::Result<c_int> {
40+
if ret == -1 {
41+
Err(io::Error::last_os_error())
42+
} else {
43+
Ok(ret)
44+
}
45+
}
46+
47+
fn set_blocking(fd: RawFd) -> io::Result<()> {
48+
let flags = cvt(unsafe { fcntl(fd, F_GETFL) })?;
49+
cvt(unsafe { fcntl(fd, F_SETFL, flags & (!O_NONBLOCK)) })?;
50+
51+
Ok(())
52+
}
53+
3854
impl Fd {
3955
pub(crate) fn as_raw_fd_or_null_fd(&self) -> Result<RawFd, Error> {
4056
use Fd::*;
4157

42-
match self {
43-
PipeReadEnd(fd) => Ok(AsRawFd::as_raw_fd(fd)),
44-
PipeWriteEnd(fd) => Ok(AsRawFd::as_raw_fd(fd)),
58+
let fd = match self {
59+
PipeReadEnd(fd) => Some(AsRawFd::as_raw_fd(fd)),
60+
PipeWriteEnd(fd) => Some(AsRawFd::as_raw_fd(fd)),
61+
62+
Borrowed(rawfd) => Some(*rawfd),
63+
Null => None,
64+
};
65+
66+
if let Some(fd) = fd {
67+
set_blocking(fd).map_err(Error::ChildIo)?;
4568

46-
Borrowed(rawfd) => Ok(*rawfd),
47-
Null => get_null_fd(),
69+
Ok(fd)
70+
} else {
71+
get_null_fd()
4872
}
4973
}
5074
}

0 commit comments

Comments
 (0)