Marc Aryan
Marc Aryan

Reputation: 3

How to read the start time data in "proc/pid/stat" to calculate the elapsed time in Linux?

My aim is to write a system-call that finds the time passed from the starting time of an ongoing process. I am researching still trying to understand. Firstly I tried the code below but it returned -1, I am not sure this was the correct way to trace the processes.

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;
        }
    }
}

Then I decided to use the data in proc/pid/stat, but I don't know how to read the start time of given pid and return.

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;
        }
    }
}

Edit

According to advices and research, I have succeed to pass the parameter pid then printed pid and name. Now trying to find start time/elapsed time.

{
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);
}

Upvotes: 0

Views: 1453

Answers (1)

halfer
halfer

Reputation: 20420

(Posted the solution on behalf of the question author, to move it from the question post).

The code I wrote is added below. I have searched where the Process Control Block is stored and found a struct named task_struct which stores many useful fields https://docs.huihoo.com/doxygen/linux/kernel/3.7/structtask__struct.html.

I have noticed that I was not able to pass the argument to the system call. Thanks to the answer on this topic How to pass parameters to Linux system call? I have done it. Lastly returned the elapsed time in seconds.

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

Upvotes: 1

Related Questions