os/fs/proc/generators/process/
stat.rs

1use alloc::{format, sync::Weak, vec::Vec};
2
3use crate::{
4    fs::proc::ContentGenerator,
5    kernel::{TaskState, TaskStruct},
6    sync::SpinLock,
7    vfs::FsError,
8};
9
10/// 为指定任务生成 /proc/\[pid\]/stat 内容的生成器
11pub struct StatGenerator {
12    task: Weak<SpinLock<TaskStruct>>,
13}
14
15impl StatGenerator {
16    pub fn new(task: Weak<SpinLock<TaskStruct>>) -> Self {
17        Self { task }
18    }
19}
20
21impl ContentGenerator for StatGenerator {
22    fn generate(&self) -> Result<Vec<u8>, FsError> {
23        let task_arc = self.task.upgrade().ok_or(FsError::NotFound)?;
24        let task = task_arc.lock();
25
26        // 状态字符
27        let state_char = match task.state {
28            TaskState::Running => 'R',
29            TaskState::Interruptible => 'S',
30            TaskState::Uninterruptible => 'D',
31            TaskState::Stopped => 'T',
32            TaskState::Zombie => 'Z',
33        };
34
35        // 获取进程名称(简化实现)
36        let name = format!("task_{}", task.tid);
37
38        // Linux /proc/\[pid\]/stat 格式(简化版)
39        // 格式参考: man 5 proc
40        let content = format!(
41            "{} ({}) {} {} {} {} 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n",
42            task.tid,   // (1) pid
43            name,       // (2) comm (进程名)
44            state_char, // (3) state
45            task.ppid,  // (4) ppid
46            task.pgid,  // (5) pgrp
47            0,          // (6) session
48                        // 后续字段暂时用 0 填充
49        );
50
51        Ok(content.into_bytes())
52    }
53}