Issue
The following code loops over the ancestors of curr_task
, all the way to the swapper
process (i.e the "most distant" ancestor of any Linux process), where it stops because swapper == swapper->parent
.
while (curr_task != curr_task->parent)
...get curr_task info
curr_task = curr_task->parent
The problem is I also want to get the swapper
process's info. There are a couple obvious ways to do this (eg goto
statement after the while loop, or a single if
statement after the loop that gets the swapper
info). However, these obvious solutions seems fairly inelegant, and so I'm looking for a more concise solution that doesn't involve the much-maligned goto
or copy/pasting code.
Solution
Here's one way to do it: use another variable.
struct task_struct *t, *prev;
t = current;
do {
// do something with t
prev = t;
t = t->parent;
} while (prev->pid != 0);
Or move that into a function:
int move_up(struct task **tp) {
int was_swapper = ((*tp)->pid == 0);
*tp = (*tp)->parent;
return was_swapper;
}
// ...
struct task_struct *t = current;
do {
// do something with t
} while (move_up(&t));
Answered By - Nate Eldredge Answer Checked By - Candace Johnson (WPSolving Volunteer)