我需要用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函数。有人能帮我吗?
发布于 2020-05-05 04:59:08
您正在使用内核代码。内核中没有C标准库!您不能包含像unistd.h这样的标准头文件,也不能使用像getppid()这样的大多数C标准库函数。
如果想要从内核模块获取当前父进程的PID,可以从current->real_parent获取。
ppid = rcu_dereference(current->real_parent)->pid;https://stackoverflow.com/questions/61601277
复制相似问题