不能在 Linux 内核模块中包含 unistd.h

Cannot include unistd.h in Linux kernel module

我需要用C在linux中使用DFS(深度优先搜索)遍历所有当前进程。我需要获取名为gedit的进程的父进程名称和父进程ID。我正在尝试使用 getppid 函数。这是代码:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>

// Not sure of these two include statements:
#include <linux/types.h>
#include <unistd.h>

/* performs a depth-first traversal of the list of tasks in the system. */
void traverse(struct task_struct *ptr) {
    struct list_head *list;
    struct task_struct *next_task;
    pid_t ppid;

    if ((thread_group_leader(ptr)) && (strcmp(ptr->comm,"gedit")==0)) {
              ppid = getppid();
              printk(KERN_INFO "PID:%d\n",ppid); }

    list_for_each(list, &ptr->children) {
        next_task = list_entry(list, struct task_struct, sibling);
        traverse(next_task);
    }
}

int simple_init(void)
{
     printk(KERN_INFO "Loading Module\n");
     printk(KERN_INFO "Gedit's parent process:\n");
     traverse(&init_task);
     return 0;
}

void simple_exit(void) {
    printk(KERN_INFO "Removing Module\n");
}

module_init( simple_init );
module_exit( simple_exit );

我得到这个错误:unistd.h没有那个文件或目录 如果我尝试包含 linux/unistd.h,我会得到 getppid 函数错误的隐式声明。

遍历有效,唯一的问题是库和 getppid 函数。谁能帮我解决这个问题?

您正在使用内核代码。内核中没有 C 标准库!您不能包含 unistd.h 这样的标准头文件,也不能使用 getppid().

这样的大多数 C 标准库函数

如果你想从内核模块中获取当前父进程的PID,你可以从current->real_parent中获取。

rcu_read_lock();
ppid = rcu_dereference(current->real_parent)->pid;
rcu_read_unlock();