【问题标题】:How to read the start time data in "proc/pid/stat" to calculate the elapsed time in Linux?如何读取“proc/pid/stat”中的开始时间数据来计算Linux中的经过时间?
【发布时间】:2020-04-14 00:36:25
【问题描述】:

我的目标是编写一个系统调用来查找从正在进行的进程的开始时间经过的时间。我正在研究仍然试图理解。首先我尝试了下面的代码,但它返回 -1,我不确定这是跟踪进程的正确方法。

asmlinkage int sys_deneme(pid_t pid)
{
    struct task_struct *task;
    struct tms *tms;
    int returnValue = 0;

//Is this correct to find a specific process?
//The code returns -1. Why it never enters if part?
    for_each_process(task){ 
        if((int)task->pid == pid){
            times(tms); 
            returnValue = returnValue + (int) tms->tms_utime +(int) tms->tms_stime+(int)tms->tms_cutime+(int)tms->tms_cstime;
            return returnValue;
        }
        else{
         return -1;
        }
    }
}

然后我决定使用proc/pid/stat中的数据,但是我不知道如何读取给定pid的开始时间并返回。

asmlinkage int sys_deneme(pid_t pid)
{
    struct task_struct *task;
    struct tms *tms;
    int returnValue = 0;

        struct kstat *stat;

    for_each_process(task){
        if((int)task->pid == pid){
            returnValue = (int)stat->btime->tv_sec;
            return returnValue;
        }
        else{
            return -1;
        }
    }
}

编辑

根据建议和研究,我已经成功传递了参数pid然后打印了pid和name。现在正在尝试查找开始时间/经过时间。

{
struct task_struct *task;

task = pid_task(find_vpid(pid),PIDTYPE_PID);

printk(KERN_INFO "pid %d \n",pid);

printk(KERN_INFO "Name: %s\n",task->comm);
}

【问题讨论】:

标签: c linux linux-kernel task system-calls


【解决方案1】:

(代表问题作者发布解决方案,将其从问题帖子中移出)

我写的代码添加在下面。我搜索了进程控制块的存储位置,发现了一个名为 task_struct 的结构,其中存储了许多有用的字段https://docs.huihoo.com/doxygen/linux/kernel/3.7/structtask__struct.html

我注意到我无法将参数传递给系统调用。感谢这个话题的答案How to pass parameters to Linux system call?我已经做到了。最后以秒为单位返回经过的时间。

SYSCALL_DEFINE1(get_elapsed_time, int, pid)
{
    struct task_struct *task; //(1)

    for_each_process(task){
        if(pid == task->pid){
            return (((ktime_get_ns())-(task->start_time))/1000000000);
        }
    }

    return -1;
}
//or 
//struct task_struct *task;
//task = pid_task(find_vpid(pid),PIDTYPE_PID);
//return (((ktime_get_ns())-(task->start_time))/1000000000);
//found ktime_get_ns() from timekeeping.h

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多