[libos] Fix the file closing issue in dup2/dup3

This commit is contained in:
LI Qing 2023-03-06 17:11:50 +08:00 committed by volcano
parent 0ac398b635
commit 573ba85634
2 changed files with 10 additions and 3 deletions

@ -23,7 +23,10 @@ pub fn do_dup2(old_fd: FileDesc, new_fd: FileDesc) -> Result<FileDesc> {
} }
if old_fd != new_fd { if old_fd != new_fd {
files.put_at(new_fd, file, false); if let Some(old_file) = files.put_at(new_fd, file, false) {
// If the file descriptor `new_fd` was previously open, close it silently.
old_file.release_advisory_locks()
}
} }
Ok(new_fd) Ok(new_fd)
} }
@ -46,6 +49,9 @@ pub fn do_dup3(old_fd: FileDesc, new_fd: FileDesc, flags: u32) -> Result<FileDes
if old_fd == new_fd { if old_fd == new_fd {
return_errno!(EINVAL, "old_fd must not be equal to new_fd"); return_errno!(EINVAL, "old_fd must not be equal to new_fd");
} }
files.put_at(new_fd, file, creation_flags.must_close_on_spawn()); if let Some(old_file) = files.put_at(new_fd, file, creation_flags.must_close_on_spawn()) {
// If the file descriptor `new_fd` was previously open, close it silently.
old_file.release_advisory_locks()
}
Ok(new_fd) Ok(new_fd)
} }

@ -86,7 +86,7 @@ impl FileTable {
min_free_fd as FileDesc min_free_fd as FileDesc
} }
pub fn put_at(&mut self, fd: FileDesc, file: FileRef, close_on_spawn: bool) { pub fn put_at(&mut self, fd: FileDesc, file: FileRef, close_on_spawn: bool) -> Option<FileRef> {
let mut table = &mut self.table; let mut table = &mut self.table;
let mut table_entry = Some(FileTableEntry::new(file, close_on_spawn)); let mut table_entry = Some(FileTableEntry::new(file, close_on_spawn));
if fd as usize >= table.len() { if fd as usize >= table.len() {
@ -96,6 +96,7 @@ impl FileTable {
if table_entry.is_none() { if table_entry.is_none() {
self.num_fds += 1; self.num_fds += 1;
} }
table_entry.map(|entry| entry.file.clone())
} }
pub fn fds(&self) -> Vec<FileDesc> { pub fn fds(&self) -> Vec<FileDesc> {