我需要使用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函数错误的隐式删除。
Traversal的作品,唯一的问题是库和getppid函数。有人可以帮我吗?
您正在使用内核代码。内核中没有C标准库!您不能包含unistd.h
之类的标准头文件,也不能使用getppid()
之类的大多数C标准库函数。
如果要从内核模块获取当前父进程的PID,则可以从current->real_parent
获取。
ppid = rcu_dereference(current->real_parent)->pid;