我需要在Linux中用DFS(Depth First Search)用C语言遍历所有当前进程,我需要获得名为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 no such file or directory如果我尝试包含linuxunistd.h,我得到了getppid函数的隐式声明错误。
遍历正常,唯一的问题是库和getppid函数。谁能帮我解决这个问题?
你正在使用内核代码。内核中没有C标准库!你不能在内核中包含标准头文件,如:"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"、"我的名字"。你不能在内核中包含标准的头文件,比如 unistd.h
或使用大多数C标准库函数,如 getppid()
.
如果你想从内核模块中获取当前父进程的PID,你可以从 current->real_parent
.
ppid = rcu_dereference(current->real_parent)->pid;