Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for_each_process - Does it iterate over the threads and the processes as well?

I would like to iterate all the tasks in the kernel (threads and processes) and print tid/pid and name using for_each_process macro:

#define for_each_process(p) \
    for (p = &init_task ; (p = next_task(p)) != &init_task ; )

How can I distinguish between thread and process?

So I'll print it like that:

 if (p->real_parent->pid == NULL)
      printk("PROCESS: name: %s pid: %d \n",p->comm,p->pid);
 else
      printk("THREAD: name: %s tid: %d \n",p->comm,p->pid);
like image 590
0x90 Avatar asked Dec 22 '12 18:12

0x90


1 Answers

The following macros are what you need:

/*
 * Careful: do_each_thread/while_each_thread is a double loop so
 *          'break' will not work as expected - use goto instead.
 */
#define do_each_thread(g, t) \
        for (g = t = &init_task ; (g = t = next_task(g)) != &init_task ; ) do

#define while_each_thread(g, t) \
        while ((t = next_thread(t)) != g)

Use them like this:

        rcu_read_lock();
        do_each_thread(g, t) {
            //...
        } while_each_thread(g, t);

        rcu_read_unlock();
like image 163
Cong Wang Avatar answered Nov 11 '22 07:11

Cong Wang