203k views
1 vote
Design a kernel module that iterates through all task in the system using the for_each_process() macro. In particular, output the task name (known as executable name), state, and process id of each task. (You will probably have to read through the task_struct structure in to obtain the names of these fields.) write this code in the module entry point so that its contents will appear in the kernel log buffer, which can be viewed using the dmesg command. To verify that your code is working correctly, compare the contents of the kernel log buffer with the output of the following command, which lists all tasks in the systemps -el

The two values should be very similar. Because tasks are dynamic, however, it is possible that a few tasks may appear in one listing but not the other.

#include

struct task_struct *task;

for_each_process(task) {
/* on each iteration task points to the next task */
}
The various fields in task_struct can then be displayed as the program loops through the for_each_process() macro.

1 Answer

3 votes

Answer:

#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/init.h>

#include <linux/sched/signal.h>

#include <linux/sched.h>

struct task_struct *task; /* Structure defined in sched.h for tasks/processes */

struct task_struct *task_child; /* Structure needed to iterate through task children */

struct list_head *list; /* Structure needed to iterate through the list in each task->children struct */

int iterate_init(void) /* Init Module */

{

printk(KERN_INFO "%s","LOADING MODULE\\"); /* good practice to log when loading/removing modules */

for_each_process( task ){ /* for_each_process() MACRO for iterating through each task in the os located in linux\sched\signal.h */

printk(KERN_INFO "\\PARENT PID: %d PROCESS: %s STATE: %ld",task->pid, task->comm, task->state);/* log parent id/executable name/state */

list_for_each(list, &task->children){ /* list_for_each MACRO to iterate through task->children */

task_child = list_entry( list, struct task_struct, sibling ); /* using list_entry to declare all vars in task_child struct */

printk(KERN_INFO "\\CHILD OF %s[%d] PID: %d PROCESS: %s STATE: %ld",task->comm, task->pid, /* log child of and child pid/name/state */

task_child->pid, task_child->comm, task_child->state);

}

printk("-----------------------------------------------------"); /*for aesthetics*/

}

return 0;

} /* End of Init Module */

void cleanup_exit(void) /* Exit Module */

{

printk(KERN_INFO "%s","REMOVING MODULE\\");

} /* End of Exit Module */

module_init(iterate_init); /* Load Module MACRO */

module_exit(cleanup_exit); /* Remove Module MACRO */

MODULE_LICENSE("GPL");

MODULE_DESCRIPTION("ITERAT

User YashC
by
5.0k points