I need to traverse all current processes with DFS(Depth First Search) in linux with C. I need to get parent process name and parent process id of the process named gedit. I'm trying to use 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.
Traversal works, the only problem is libraries and getppid function. Can anyone help me with this?
You're working with kernel code. There's no C standard library in the kernel! You cannot include standard headers like unistd.h
or use most C standard library functions like 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
.
ppid = rcu_dereference(current->real_parent)->pid;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.