mod.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. use core::intrinsics::size_of;
  2. use alloc::{
  3. borrow::ToOwned,
  4. collections::BTreeMap,
  5. format,
  6. string::{String, ToString},
  7. sync::{Arc, Weak},
  8. vec::Vec,
  9. };
  10. use crate::{
  11. filesystem::vfs::{
  12. core::{generate_inode_id, ROOT_INODE},
  13. FileType,
  14. },
  15. include::bindings::bindings::{pid_t, process_find_pcb_by_pid},
  16. kerror,
  17. libs::spinlock::{SpinLock, SpinLockGuard},
  18. syscall::SystemError,
  19. time::TimeSpec,
  20. };
  21. use super::vfs::{
  22. file::{FileMode, FilePrivateData},
  23. FileSystem, FsInfo, IndexNode, InodeId, Metadata, PollStatus,
  24. };
  25. /// @brief 进程文件类型
  26. /// @usage 用于定义进程文件夹下的各类文件类型
  27. #[derive(Debug)]
  28. #[repr(u8)]
  29. pub enum ProcFileType {
  30. ///展示进程状态信息
  31. ProcStatus = 0,
  32. //todo: 其他文件类型
  33. ///默认文件类型
  34. Default,
  35. }
  36. impl From<u8> for ProcFileType {
  37. fn from(value: u8) -> Self {
  38. match value {
  39. 0 => ProcFileType::ProcStatus,
  40. _ => ProcFileType::Default,
  41. }
  42. }
  43. }
  44. /// @brief 节点私有信息结构体
  45. /// @usage 用于传入各类文件所需的信息
  46. #[derive(Debug)]
  47. pub struct InodeInfo {
  48. ///进程的pid
  49. pid: i64,
  50. ///文件类型
  51. ftype: ProcFileType,
  52. //其他需要传入的信息在此定义
  53. }
  54. /// @brief procfs的inode名称的最大长度
  55. const PROCFS_MAX_NAMELEN: usize = 64;
  56. /// @brief procfs文件系统的Inode结构体
  57. #[derive(Debug)]
  58. pub struct LockedProcFSInode(SpinLock<ProcFSInode>);
  59. /// @brief procfs文件系统结构体
  60. #[derive(Debug)]
  61. pub struct ProcFS {
  62. /// procfs的root inode
  63. root_inode: Arc<LockedProcFSInode>,
  64. }
  65. #[derive(Debug, Clone)]
  66. pub struct ProcfsFilePrivateData {
  67. data: Vec<u8>,
  68. }
  69. impl ProcfsFilePrivateData {
  70. pub fn new() -> Self {
  71. return ProcfsFilePrivateData { data: Vec::new() };
  72. }
  73. }
  74. /// @brief procfs文件系统的Inode结构体(不包含锁)
  75. #[derive(Debug)]
  76. pub struct ProcFSInode {
  77. /// 指向父Inode的弱引用
  78. parent: Weak<LockedProcFSInode>,
  79. /// 指向自身的弱引用
  80. self_ref: Weak<LockedProcFSInode>,
  81. /// 子Inode的B树
  82. children: BTreeMap<String, Arc<LockedProcFSInode>>,
  83. /// 当前inode的数据部分
  84. data: Vec<u8>,
  85. /// 当前inode的元数据
  86. metadata: Metadata,
  87. /// 指向inode所在的文件系统对象的指针
  88. fs: Weak<ProcFS>,
  89. /// 储存私有信息
  90. fdata: InodeInfo,
  91. }
  92. /// 对ProcFSInode实现获取各类文件信息的函数
  93. impl ProcFSInode {
  94. /// @brief 去除Vec中所有的\0,并在结尾添加\0
  95. #[inline]
  96. fn trim_string(&self, data: &mut Vec<u8>) {
  97. data.drain_filter(|x: &mut u8| *x == 0);
  98. data.push(0);
  99. }
  100. // todo:其他数据获取函数实现
  101. /// @brief 打开status文件
  102. ///
  103. fn open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> {
  104. // 获取该pid对应的pcb结构体
  105. let pid: &i64 = &self.fdata.pid;
  106. let pcb = unsafe { process_find_pcb_by_pid(*pid).as_mut() };
  107. let pcb = if pcb.is_none() {
  108. kerror!(
  109. "ProcFS: Cannot find pcb for pid {} when opening its 'status' file.",
  110. pid
  111. );
  112. return Err(SystemError::ESRCH);
  113. } else {
  114. pcb.unwrap()
  115. };
  116. // 传入数据
  117. let pdata: &mut Vec<u8> = &mut pdata.data;
  118. // !!!!!由于目前有bug,不能获取到pcb的name,因此暂时用'Unknown'代替
  119. let tmp_name: Vec<u8> = "Unknown".as_bytes().to_vec();
  120. // kdebug!("pcb.name={:?}", pcb.name);
  121. // let mut tmp_name: Vec<u8> = Vec::with_capacity(pcb.name.len());
  122. // for val in pcb.name.iter() {
  123. // tmp_name.push(*val as u8);
  124. // }
  125. pdata.append(
  126. &mut format!(
  127. "Name:\t{}",
  128. String::from_utf8(tmp_name).unwrap_or("NULL".to_string())
  129. )
  130. .as_bytes()
  131. .to_owned(),
  132. );
  133. pdata.append(&mut format!("\nstate:\t{}", pcb.state).as_bytes().to_owned());
  134. pdata.append(&mut format!("\npid:\t{}", pcb.pid).as_bytes().to_owned());
  135. pdata.append(
  136. &mut format!("\nPpid:\t{}", unsafe { *pcb.parent_pcb }.pid)
  137. .as_bytes()
  138. .to_owned(),
  139. );
  140. pdata.append(&mut format!("\ncpu_id:\t{}", pcb.cpu_id).as_bytes().to_owned());
  141. pdata.append(
  142. &mut format!("\npriority:\t{}", pcb.priority)
  143. .as_bytes()
  144. .to_owned(),
  145. );
  146. pdata.append(
  147. &mut format!("\npreempt:\t{}", pcb.preempt_count)
  148. .as_bytes()
  149. .to_owned(),
  150. );
  151. pdata.append(
  152. &mut format!("\nvrtime:\t{}", pcb.virtual_runtime)
  153. .as_bytes()
  154. .to_owned(),
  155. );
  156. // 当前进程运行过程中占用内存的峰值
  157. let hiwater_vm: u64 =
  158. unsafe { *(*pcb.mm).vmas }.vm_end - unsafe { *(*pcb.mm).vmas }.vm_start;
  159. // 进程数据段的大小
  160. let text: u64 = unsafe { *pcb.mm }.code_addr_end - unsafe { *pcb.mm }.code_addr_start;
  161. // 进程代码的大小
  162. let data: u64 = unsafe { *pcb.mm }.data_addr_end - unsafe { *pcb.mm }.data_addr_start;
  163. pdata.append(
  164. &mut format!("\nVmPeak:\t{} kB", hiwater_vm)
  165. .as_bytes()
  166. .to_owned(),
  167. );
  168. pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned());
  169. pdata.append(&mut format!("\nVmExe:\t{} kB\n", text).as_bytes().to_owned());
  170. // 去除多余的\0
  171. self.trim_string(pdata);
  172. return Ok((pdata.len() * size_of::<u8>()) as i64);
  173. }
  174. /// status文件读取函数
  175. fn read_status(
  176. &self,
  177. offset: usize,
  178. len: usize,
  179. buf: &mut [u8],
  180. _pdata: &mut ProcfsFilePrivateData,
  181. ) -> Result<usize, SystemError> {
  182. let start = _pdata.data.len().min(offset);
  183. let end = _pdata.data.len().min(offset + len);
  184. // buffer空间不足
  185. if buf.len() < (end - start) {
  186. return Err(SystemError::ENOBUFS);
  187. }
  188. // 拷贝数据
  189. let src = &_pdata.data[start..end];
  190. buf[0..src.len()].copy_from_slice(src);
  191. return Ok(src.len());
  192. }
  193. }
  194. impl FileSystem for ProcFS {
  195. fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> {
  196. return self.root_inode.clone();
  197. }
  198. fn info(&self) -> FsInfo {
  199. return FsInfo {
  200. blk_dev_id: 0,
  201. max_name_len: PROCFS_MAX_NAMELEN,
  202. };
  203. }
  204. fn as_any_ref(&self) -> &dyn core::any::Any {
  205. self
  206. }
  207. }
  208. impl ProcFS {
  209. pub fn new() -> Arc<Self> {
  210. // 初始化root inode
  211. let root: Arc<LockedProcFSInode> =
  212. Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode {
  213. parent: Weak::default(),
  214. self_ref: Weak::default(),
  215. children: BTreeMap::new(),
  216. data: Vec::new(),
  217. metadata: Metadata {
  218. dev_id: 0,
  219. inode_id: generate_inode_id(),
  220. size: 0,
  221. blk_size: 0,
  222. blocks: 0,
  223. atime: TimeSpec::default(),
  224. mtime: TimeSpec::default(),
  225. ctime: TimeSpec::default(),
  226. file_type: FileType::Dir,
  227. mode: 0o777,
  228. nlinks: 1,
  229. uid: 0,
  230. gid: 0,
  231. raw_dev: 0,
  232. },
  233. fs: Weak::default(),
  234. fdata: InodeInfo {
  235. pid: 0,
  236. ftype: ProcFileType::Default,
  237. },
  238. })));
  239. let result: Arc<ProcFS> = Arc::new(ProcFS { root_inode: root });
  240. // 对root inode加锁,并继续完成初始化工作
  241. let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock();
  242. root_guard.parent = Arc::downgrade(&result.root_inode);
  243. root_guard.self_ref = Arc::downgrade(&result.root_inode);
  244. root_guard.fs = Arc::downgrade(&result);
  245. // 释放锁
  246. drop(root_guard);
  247. return result;
  248. }
  249. /// @brief 进程注册函数
  250. /// @usage 在进程中调用并创建进程对应文件
  251. pub fn register_pid(&self, pid: i64) -> Result<(), SystemError> {
  252. // 获取当前inode
  253. let proc: Arc<dyn IndexNode> = self.root_inode();
  254. // 创建对应进程文件夹
  255. let _pf: Arc<dyn IndexNode> = proc.create(&pid.to_string(), FileType::Dir, 0o777)?;
  256. // 创建相关文件
  257. // status文件
  258. let binding: Arc<dyn IndexNode> = _pf.create("status", FileType::File, 0o777)?;
  259. let _sf: &LockedProcFSInode = binding
  260. .as_any_ref()
  261. .downcast_ref::<LockedProcFSInode>()
  262. .unwrap();
  263. _sf.0.lock().fdata.pid = pid;
  264. _sf.0.lock().fdata.ftype = ProcFileType::ProcStatus;
  265. //todo: 创建其他文件
  266. return Ok(());
  267. }
  268. /// @brief 解除进程注册
  269. ///
  270. pub fn unregister_pid(&self, pid: i64) -> Result<(), SystemError> {
  271. // 获取当前inode
  272. let proc: Arc<dyn IndexNode> = self.root_inode();
  273. // 获取进程文件夹
  274. let pid_dir: Arc<dyn IndexNode> = proc.find(&format!("{}", pid))?;
  275. // 删除进程文件夹下文件
  276. pid_dir.unlink("status")?;
  277. // 查看进程文件是否还存在
  278. // let pf= pid_dir.find("status").expect("Cannot find status");
  279. // 删除进程文件夹
  280. proc.unlink(&format!("{}", pid))?;
  281. return Ok(());
  282. }
  283. }
  284. impl IndexNode for LockedProcFSInode {
  285. fn open(&self, data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
  286. // 加锁
  287. let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  288. // 如果inode类型为文件夹,则直接返回成功
  289. if let FileType::Dir = inode.metadata.file_type {
  290. return Ok(());
  291. }
  292. let mut private_data = ProcfsFilePrivateData::new();
  293. // 根据文件类型获取相应数据
  294. let file_size = match inode.fdata.ftype {
  295. ProcFileType::ProcStatus => inode.open_status(&mut private_data)?,
  296. _ => {
  297. todo!()
  298. }
  299. };
  300. *data = FilePrivateData::Procfs(private_data);
  301. // 更新metadata里面的文件大小数值
  302. inode.metadata.size = file_size;
  303. return Ok(());
  304. }
  305. fn close(&self, data: &mut FilePrivateData) -> Result<(), SystemError> {
  306. let guard: SpinLockGuard<ProcFSInode> = self.0.lock();
  307. // 如果inode类型为文件夹,则直接返回成功
  308. if let FileType::Dir = guard.metadata.file_type {
  309. return Ok(());
  310. }
  311. // 获取数据信息
  312. let private_data = match data {
  313. FilePrivateData::Procfs(p) => p,
  314. _ => {
  315. panic!("ProcFS: FilePrivateData mismatch!");
  316. }
  317. };
  318. // 释放资源
  319. drop(private_data);
  320. return Ok(());
  321. }
  322. fn read_at(
  323. &self,
  324. offset: usize,
  325. len: usize,
  326. buf: &mut [u8],
  327. data: &mut FilePrivateData,
  328. ) -> Result<usize, SystemError> {
  329. if buf.len() < len {
  330. return Err(SystemError::EINVAL);
  331. }
  332. // 加锁
  333. let inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  334. // 检查当前inode是否为一个文件夹,如果是的话,就返回错误
  335. if inode.metadata.file_type == FileType::Dir {
  336. return Err(SystemError::EISDIR);
  337. }
  338. // 获取数据信息
  339. let private_data = match data {
  340. FilePrivateData::Procfs(p) => p,
  341. _ => {
  342. panic!("ProcFS: FilePrivateData mismatch!");
  343. }
  344. };
  345. // 根据文件类型读取相应数据
  346. match inode.fdata.ftype {
  347. ProcFileType::ProcStatus => return inode.read_status(offset, len, buf, private_data),
  348. ProcFileType::Default => (),
  349. };
  350. // 默认读取
  351. let start = inode.data.len().min(offset);
  352. let end = inode.data.len().min(offset + len);
  353. // buffer空间不足
  354. if buf.len() < (end - start) {
  355. return Err(SystemError::ENOBUFS);
  356. }
  357. // 拷贝数据
  358. let src = &inode.data[start..end];
  359. buf[0..src.len()].copy_from_slice(src);
  360. return Ok(src.len());
  361. }
  362. fn write_at(
  363. &self,
  364. _offset: usize,
  365. _len: usize,
  366. _buf: &[u8],
  367. _data: &mut FilePrivateData,
  368. ) -> Result<usize, SystemError> {
  369. return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
  370. }
  371. fn poll(&self) -> Result<PollStatus, SystemError> {
  372. // 加锁
  373. let inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  374. // 检查当前inode是否为一个文件夹,如果是的话,就返回错误
  375. if inode.metadata.file_type == FileType::Dir {
  376. return Err(SystemError::EISDIR);
  377. }
  378. return Ok(PollStatus {
  379. flags: PollStatus::READ_MASK,
  380. });
  381. }
  382. fn fs(&self) -> Arc<dyn FileSystem> {
  383. return self.0.lock().fs.upgrade().unwrap();
  384. }
  385. fn as_any_ref(&self) -> &dyn core::any::Any {
  386. self
  387. }
  388. fn metadata(&self) -> Result<Metadata, SystemError> {
  389. let inode = self.0.lock();
  390. let metadata = inode.metadata.clone();
  391. return Ok(metadata);
  392. }
  393. fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> {
  394. let mut inode = self.0.lock();
  395. inode.metadata.atime = metadata.atime;
  396. inode.metadata.mtime = metadata.mtime;
  397. inode.metadata.ctime = metadata.ctime;
  398. inode.metadata.mode = metadata.mode;
  399. inode.metadata.uid = metadata.uid;
  400. inode.metadata.gid = metadata.gid;
  401. return Ok(());
  402. }
  403. fn resize(&self, len: usize) -> Result<(), SystemError> {
  404. let mut inode = self.0.lock();
  405. if inode.metadata.file_type == FileType::File {
  406. inode.data.resize(len, 0);
  407. return Ok(());
  408. } else {
  409. return Err(SystemError::EINVAL);
  410. }
  411. }
  412. fn create_with_data(
  413. &self,
  414. name: &str,
  415. file_type: FileType,
  416. mode: u32,
  417. data: usize,
  418. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  419. // 获取当前inode
  420. let mut inode = self.0.lock();
  421. // 如果当前inode不是文件夹,则返回
  422. if inode.metadata.file_type != FileType::Dir {
  423. return Err(SystemError::ENOTDIR);
  424. }
  425. // 如果有重名的,则返回
  426. if inode.children.contains_key(name) {
  427. return Err(SystemError::EEXIST);
  428. }
  429. // 创建inode
  430. let result: Arc<LockedProcFSInode> =
  431. Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode {
  432. parent: inode.self_ref.clone(),
  433. self_ref: Weak::default(),
  434. children: BTreeMap::new(),
  435. data: Vec::new(),
  436. metadata: Metadata {
  437. dev_id: 0,
  438. inode_id: generate_inode_id(),
  439. size: 0,
  440. blk_size: 0,
  441. blocks: 0,
  442. atime: TimeSpec::default(),
  443. mtime: TimeSpec::default(),
  444. ctime: TimeSpec::default(),
  445. file_type: file_type,
  446. mode: mode,
  447. nlinks: 1,
  448. uid: 0,
  449. gid: 0,
  450. raw_dev: data,
  451. },
  452. fs: inode.fs.clone(),
  453. fdata: InodeInfo {
  454. pid: 0,
  455. ftype: ProcFileType::Default,
  456. },
  457. })));
  458. // 初始化inode的自引用的weak指针
  459. result.0.lock().self_ref = Arc::downgrade(&result);
  460. // 将子inode插入父inode的B树中
  461. inode.children.insert(String::from(name), result.clone());
  462. return Ok(result);
  463. }
  464. fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
  465. let other: &LockedProcFSInode = other
  466. .downcast_ref::<LockedProcFSInode>()
  467. .ok_or(SystemError::EPERM)?;
  468. let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  469. let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock();
  470. // 如果当前inode不是文件夹,那么报错
  471. if inode.metadata.file_type != FileType::Dir {
  472. return Err(SystemError::ENOTDIR);
  473. }
  474. // 如果另一个inode是文件夹,那么也报错
  475. if other_locked.metadata.file_type == FileType::Dir {
  476. return Err(SystemError::EISDIR);
  477. }
  478. // 如果当前文件夹下已经有同名文件,也报错。
  479. if inode.children.contains_key(name) {
  480. return Err(SystemError::EEXIST);
  481. }
  482. inode
  483. .children
  484. .insert(String::from(name), other_locked.self_ref.upgrade().unwrap());
  485. // 增加硬链接计数
  486. other_locked.metadata.nlinks += 1;
  487. return Ok(());
  488. }
  489. fn unlink(&self, name: &str) -> Result<(), SystemError> {
  490. let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  491. // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录
  492. if inode.metadata.file_type != FileType::Dir {
  493. return Err(SystemError::ENOTDIR);
  494. }
  495. // 不允许删除当前文件夹,也不允许删除上一个目录
  496. if name == "." || name == ".." {
  497. return Err(SystemError::ENOTEMPTY);
  498. }
  499. // 获得要删除的文件的inode
  500. let to_delete = inode.children.get(name).ok_or(SystemError::ENOENT)?;
  501. // 减少硬链接计数
  502. to_delete.0.lock().metadata.nlinks -= 1;
  503. // 在当前目录中删除这个子目录项
  504. inode.children.remove(name);
  505. return Ok(());
  506. }
  507. fn move_(
  508. &self,
  509. _old_name: &str,
  510. _target: &Arc<dyn IndexNode>,
  511. _new_name: &str,
  512. ) -> Result<(), SystemError> {
  513. return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
  514. }
  515. fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
  516. let inode = self.0.lock();
  517. if inode.metadata.file_type != FileType::Dir {
  518. return Err(SystemError::ENOTDIR);
  519. }
  520. match name {
  521. "" | "." => {
  522. return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?);
  523. }
  524. ".." => {
  525. return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?);
  526. }
  527. name => {
  528. // 在子目录项中查找
  529. return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone());
  530. }
  531. }
  532. }
  533. fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> {
  534. let inode: SpinLockGuard<ProcFSInode> = self.0.lock();
  535. if inode.metadata.file_type != FileType::Dir {
  536. return Err(SystemError::ENOTDIR);
  537. }
  538. match ino {
  539. 0 => {
  540. return Ok(String::from("."));
  541. }
  542. 1 => {
  543. return Ok(String::from(".."));
  544. }
  545. ino => {
  546. // 暴力遍历所有的children,判断inode id是否相同
  547. // TODO: 优化这里,这个地方性能很差!
  548. let mut key: Vec<String> = inode
  549. .children
  550. .keys()
  551. .filter(|k| inode.children.get(*k).unwrap().0.lock().metadata.inode_id == ino)
  552. .cloned()
  553. .collect();
  554. match key.len() {
  555. 0=>{return Err(SystemError::ENOENT);}
  556. 1=>{return Ok(key.remove(0));}
  557. _ => panic!("Procfs get_entry_name: key.len()={key_len}>1, current inode_id={inode_id}, to find={to_find}", key_len=key.len(), inode_id = inode.metadata.inode_id, to_find=ino)
  558. }
  559. }
  560. }
  561. }
  562. fn list(&self) -> Result<Vec<String>, SystemError> {
  563. let info = self.metadata()?;
  564. if info.file_type != FileType::Dir {
  565. return Err(SystemError::ENOTDIR);
  566. }
  567. let mut keys: Vec<String> = Vec::new();
  568. keys.push(String::from("."));
  569. keys.push(String::from(".."));
  570. keys.append(&mut self.0.lock().children.keys().cloned().collect());
  571. return Ok(keys);
  572. }
  573. }
  574. #[no_mangle]
  575. pub extern "C" fn rs_procfs_register_pid(pid: pid_t) -> u64 {
  576. let r = procfs_register_pid(pid);
  577. if r.is_ok() {
  578. return 0;
  579. } else {
  580. return r.unwrap_err() as u64;
  581. }
  582. }
  583. /// @brief 向procfs注册进程
  584. pub fn procfs_register_pid(pid: pid_t) -> Result<(), SystemError> {
  585. let procfs_inode = ROOT_INODE().find("proc")?;
  586. let procfs_inode = procfs_inode
  587. .downcast_ref::<LockedProcFSInode>()
  588. .expect("Failed to find procfs' root inode");
  589. let fs = procfs_inode.fs();
  590. let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap();
  591. // 调用注册函数
  592. procfs.register_pid(pid)?;
  593. return Ok(());
  594. }
  595. #[no_mangle]
  596. pub extern "C" fn rs_procfs_unregister_pid(pid: pid_t) -> u64 {
  597. let r = procfs_unregister_pid(pid);
  598. if r.is_ok() {
  599. return 0;
  600. } else {
  601. return r.unwrap_err() as u64;
  602. }
  603. }
  604. /// @brief 在ProcFS中,解除进程的注册
  605. pub fn procfs_unregister_pid(pid: pid_t) -> Result<(), SystemError> {
  606. // 获取procfs实例
  607. let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?;
  608. let procfs_inode: &LockedProcFSInode = procfs_inode
  609. .downcast_ref::<LockedProcFSInode>()
  610. .expect("Failed to find procfs' root inode");
  611. let fs: Arc<dyn FileSystem> = procfs_inode.fs();
  612. let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap();
  613. // 调用解除注册函数
  614. return procfs.unregister_pid(pid);
  615. }