简体   繁体   English

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

[英]Cannot include unistd.h in Linux kernel module

I need to traverse all current processes with DFS(Depth First Search) in linux with C.我需要使用 C 在 linux 中使用 DFS(深度优先搜索)遍历所有当前进程。 I need to get parent process name and parent process id of the process named gedit.我需要获取名为 gedit 的进程的父进程名称和父进程 ID。 I'm trying to use getppid function.我正在尝试使用 getppid function。 Here is the code:这是代码:

#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 );

I get this error: unistd.h no such file or directory If I try to include linux/unistd.h, I get implicit decleration of getppid function error.我得到这个错误: unistd.h 没有这样的文件或目录 如果我尝试包含 linux/unistd.h,我得到 getppid function 错误的隐式声明。

Traversal works, the only problem is libraries and getppid function.遍历工作,唯一的问题是库和 getppid function。 Can anyone help me with this?谁能帮我这个?

You're working with kernel code.您正在使用 kernel 代码。 There's no C standard library in the kernel!内核中没有 C 标准库! You cannot include standard headers like unistd.h or use most C standard library functions like getppid() .您不能包含unistd.h之类的标准头文件或使用大多数 C 标准库函数(例如getppid()

If you want to get the PID of the current parent process from a kernel module you can get it from current->real_parent .如果您想从 kernel 模块获取当前父进程的 PID,您可以从current->real_parent获取它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM