xref: /DragonOS/kernel/src/process/stdio.rs (revision 52dc4c3ee87b31fee4f567f776fd8ad58fbfd9a5)
1 use system_error::SystemError;
2 
3 use crate::{
4     driver::tty::virtual_terminal::vc_manager,
5     filesystem::vfs::{
6         file::{File, FileMode},
7         ROOT_INODE,
8     },
9     process::{Pid, ProcessManager},
10 };
11 
12 /// @brief 初始化pid=1的进程的stdio
13 pub fn stdio_init() -> Result<(), SystemError> {
14     if ProcessManager::current_pcb().pid() != Pid(1) {
15         return Err(SystemError::EPERM);
16     }
17     let tty_path = format!(
18         "/dev/{}",
19         vc_manager()
20             .current_vc_tty_name()
21             .expect("Init stdio: can't get tty name")
22     );
23     let tty_inode = ROOT_INODE()
24         .lookup(&tty_path)
25         .unwrap_or_else(|_| panic!("Init stdio: can't find {}", tty_path));
26 
27     let stdin =
28         File::new(tty_inode.clone(), FileMode::O_RDONLY).expect("Init stdio: can't create stdin");
29     let stdout =
30         File::new(tty_inode.clone(), FileMode::O_WRONLY).expect("Init stdio: can't create stdout");
31     let stderr = File::new(tty_inode.clone(), FileMode::O_WRONLY | FileMode::O_SYNC)
32         .expect("Init stdio: can't create stderr");
33 
34     /*
35        按照规定,进程的文件描述符数组的前三个位置,分别是stdin, stdout, stderr
36     */
37     assert_eq!(
38         ProcessManager::current_pcb()
39             .fd_table()
40             .write()
41             .alloc_fd(stdin, None)
42             .unwrap(),
43         0
44     );
45     assert_eq!(
46         ProcessManager::current_pcb()
47             .fd_table()
48             .write()
49             .alloc_fd(stdout, None)
50             .unwrap(),
51         1
52     );
53     assert_eq!(
54         ProcessManager::current_pcb()
55             .fd_table()
56             .write()
57             .alloc_fd(stderr, None)
58             .unwrap(),
59         2
60     );
61     return Ok(());
62 }
63