// user/src/bin/filetest_simple.rs
pub fn main() -> i32 {
let test_str = "Hello, world!";
let filea = "filea\0";
// Create file filea, return file descriptor fd (signed integer)
let fd = open(filea, OpenFlags::CREATE | OpenFlags::WRONLY);
write(fd, test_str.as_bytes()); // write test_str to the file
close(fd); // close the file
let fd = open(filea, OpenFlags::RDONLY); // open the file in read-only mode
let mut buffer = [0u8; 100]; // 100 byte array buffer
let read_len = read(fd, &mut buffer) as usize;// read file content into the buffer
close(fd); // close the file
}
Outline
Lab objectives and steps
Code structure
Application design
4. Kernel programming
Core data structure
File management mechanism
Core data structure
Process management files
Directories, files
Inodes
File descriptor
File descriptor table
Core data structure
Files are located in the root directory ROOT_INODE
The content of a directory is an array of DirEntry
read_at and write_at convert the file offset and buf length to a series of block numbers, then read and write data blocks through get_block_cache.
get_block_id method shows the most important function of DiskInode (i.e., indexing data block). It can find the number of the block used to save the file content, so that subsequent access to this data block can be performed
sys_close : hange the corresponding item in the process control block's file descriptor table to None, indicating that it is already free. This also reduces the reference count of the file. When the reference count is reduced to 0, the resources occupied by the file will be automatically recycled
Load application based on the file
Load application based on the file (ELF executable file format)
When obtaining the ELF file data of the application, first call the open_file function to open the application file in read-only mode and obtain its corresponding OSInode. Then use OSInode::read_all to read all the data of the file into a vector all_data
Reading and writing files
Based on file abstract interface and file descriptor table
Can handle basic file reading and writing according to unstructured byte stream
The operating system finds a file in the file descriptor table of the current process through the file descriptor, and does not need to care about the specific type of the file.
Read and write files
Based on the file abstraction interface and file descriptor table
Basic file reading and writing can be processed according to the unstructured byte stream