Skip to content

Commit 10e68bf

Browse files
committed
Prevent file descriptor leak in the spawned child
After forking the child process, the file descriptors for the master and slave aren't closed since we created these descriptors ourselves (Rust sets CLOEXEC on any fds created in the stdlib). Signed-off-by: Kieran Siek <[email protected]>
1 parent cee87fc commit 10e68bf

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/process.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use nix::libc::{STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO};
77
use nix::pty::{grantpt, posix_openpt, unlockpt, PtyMaster};
88
pub use nix::sys::{signal, wait};
99
use nix::sys::{stat, termios};
10-
use nix::unistd::{dup, dup2, fork, setsid, ForkResult, Pid};
10+
use nix::unistd::{close, dup, dup2, fork, setsid, ForkResult, Pid};
1111
use std;
1212
use std::fs::File;
1313
use std::os::unix::io::{AsRawFd, FromRawFd};
@@ -97,6 +97,9 @@ impl PtyProcess {
9797

9898
match unsafe { fork()? } {
9999
ForkResult::Child => {
100+
// Avoid leaking master fd
101+
close(master_fd.as_raw_fd())?;
102+
100103
setsid()?; // create new session with child as session leader
101104
let slave_fd = open(
102105
std::path::Path::new(&slave_name),
@@ -109,6 +112,11 @@ impl PtyProcess {
109112
dup2(slave_fd, STDOUT_FILENO)?;
110113
dup2(slave_fd, STDERR_FILENO)?;
111114

115+
// Avoid leaking slave fd
116+
if slave_fd > STDERR_FILENO {
117+
close(slave_fd)?;
118+
}
119+
112120
// set echo off
113121
let mut flags = termios::tcgetattr(STDIN_FILENO)?;
114122
flags.local_flags &= !termios::LocalFlags::ECHO;

0 commit comments

Comments
 (0)