Search

using "for_each_process" in proc entry

The linux kernel, as any other system, has a lot of proccesses running at any given time.
The task_struct structure defined in sched.h stores all the details of every process that exists in the system, and all the processes in turn are stored in a circular double linked list.
Just to undertand the how to access the fields of task_struct and iterate through the various tasks in the system, here is a simlple module that creates a proc entry which when read, lists out all name and pid of all the processes running currently.

The code makes use of a function called "for_each_process" which is defined in "linux/sched.h". This function iterate through the list of all the processes.

################################################
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include<linux/sched.h>


int read_proc(char *buf,char **start,off_t offset,int count,int *eof,void *data )
{
int len=0;
struct task_struct *task_list;


for_each_process(task_list) {

       len  += sprintf(buf+len, "\n %s %d \n",task_list->comm,task_list->pid);
  }
  
return len;
}

void create_new_proc_entry()
{
create_proc_read_entry("ps_list",0,NULL,read_proc,NULL);

}


int functn_init (void) {
    int ret;
   
    create_new_proc_entry();
    return 0;
}

void functn_cleanup(void) {
    remove_proc_entry("proc_entry",NULL);
}

MODULE_LICENSE("GPL");   
module_init(functn_init);
module_exit(functn_cleanup);

################################################

In the read_proc function, "for_each_process" is called, which assigns to the variable task_list, which is of the kind "struct task_struct", the task_struct structure of one process after another as they are stored in the linked list in the kernel.
The task_list in turn is used to print the name ,task_list->comm, and the pid, task_list->pid of the process.

To see the output use the following makefile.

#############################################
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
obj-m := proces_listdo.o
PWD := $(shell pwd)
all:
    make -C $(KERNELDIR) M=$(PWD) modules
clean:
    rm *.o *.mod.c *.order *.markers
###############################################

Run the following commands

$ make
$sudo insmod process_list.ko (depends on what name you have given to the c file)
$ cat /proc/ps_list

In the output you should see a list of process names and  their pids for eg.

init 1

 kthreadd 2

 migration/0 3

 ksoftirqd/0 4

 watchdog/0 5

 events/0 6

 khelper 7



To understand about proc entries and creating proc entries you can refer to the posts "Creating proc entry"

Follow by Email