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