【问题标题】:Kernel: Right way to check if process is running in c [duplicate]内核:检查进程是否在c中运行的正确方法[重复]
【发布时间】:2014-02-11 03:18:55
【问题描述】:

我想检查我拥有的 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() 在内核中不可用。有没有其他方法可以做到这一点?

【问题讨论】:

  • 在某种程度上是的,但我认为 Christophe 的回答和我的 sn-p 可能对其他用户有帮助
  • 此问题将保持与副本的链接,因此如果问题作为副本关闭,人们可以看到您的答案和问题。如果它关闭了,请不要灰心。

标签: c linux process linux-kernel kernel


【解决方案1】:

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

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

【讨论】:

    【解决方案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);
    }
    

    【讨论】:

    • 在您的else-block 中,task 指针可能变得无效(已释放)。如果argument 假定task-&gt;pid(取消引用) - 它可能是use-after-free BUGpid_task() 应该在 RCU 临界区中使用。
    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 2017-06-10
    • 2012-07-10
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多