fix close_on_spawn and file_actions

This commit is contained in:
WangRunji 2019-04-12 14:27:48 +08:00
parent 6d432b0a03
commit 80a73eaa0d
2 changed files with 16 additions and 24 deletions

@ -4,7 +4,7 @@ use std;
pub type FileDesc = u32;
#[derive(Debug, Default)]
#[derive(Debug, Default, Clone)]
#[repr(C)]
pub struct FileTable {
table: Vec<Option<FileTableEntry>>,
@ -123,30 +123,19 @@ impl FileTable {
None => errno!(EBADF, "Invalid file descriptor"),
}
}
}
impl Clone for FileTable {
fn clone(&self) -> FileTable {
// Only clone file descriptors that are not close-on-spawn
let mut num_cloned_fds = 0;
let cloned_table = self
.table
.iter()
.map(|entry| match entry {
Some(file_table_entry) => match file_table_entry.close_on_spawn {
false => {
num_cloned_fds += 1;
Some(file_table_entry.clone())
}
true => None,
},
None => None,
})
.collect();
FileTable {
table: cloned_table,
num_fds: num_cloned_fds,
/// Remove file descriptors that are close-on-spawn
pub fn close_on_spawn(&mut self) {
for entry in self.table.iter_mut() {
let need_close = if let Some(entry) = entry {
entry.close_on_spawn
} else {
false
};
if need_close {
*entry = None;
self.num_fds -= 1;
}
}
}
}

@ -87,6 +87,7 @@ fn init_files(parent_ref: &ProcessRef, file_actions: &[FileAction]) -> Result<Fi
let parent = parent_ref.lock().unwrap();
let should_inherit_file_table = parent.get_pid() > 0;
if should_inherit_file_table {
// Fork: clone file table
let mut cloned_file_table = parent.get_files().lock().unwrap().clone();
// Perform file actions to modify the cloned file table
for file_action in file_actions {
@ -102,6 +103,8 @@ fn init_files(parent_ref: &ProcessRef, file_actions: &[FileAction]) -> Result<Fi
}
}
}
// Exec: close fd with close_on_spawn
cloned_file_table.close_on_spawn();
return Ok(cloned_file_table);
}
drop(parent);