内核:检查进程是否在c中运行的正确方法

时间:2014-01-21 13:33:05

标签: c linux process linux-kernel kernel

我想检查我的pid进程是否正在从内核扩展运行。

在用户空间中,这很简单:

if (kill(pid, 0) == 0) {
printf("Process %d is running\n", pid);
} else if (errno == ESRCH) {
printf("Process %d is not running\n", pid);
} else {
printf("This shouldn't happen oO\n");

但不知何故kill()在内核中不可用。有没有其他方法可以做到这一点?

2 个答案:

答案 0 :(得分:5)

您可以使用pid_task()get_pid_task()获取指向流程struct task_struct的指针。如果调用返回NULL,则该进程不存在。

请注意,您可能需要小心,因为 pid 可能已被回收,现在由其他进程使用。

答案 1 :(得分:2)

在克里斯托夫的回答之后,我找到了解决这个问题的方法。

//necessary imports
#include <linux/sched.h> 
#include <linux/pid.h> 
//Rest of your module
pid_t pid = myPid; //integer value of pid
struct pid *pid_struct = find_get_pid(pid); //function to find the pid_struct
struct task_struct *task = pid_task(pid_struct,PIDTYPE_PID); //find the task_struct

if (task == NULL)
{
    printk (KERN_INFO "Process with pid %d is not running \n",argument);
}
else{
    printk (KERN_INFO "Process with pid %d is running \n",argument);
}
相关问题