1

From Understanding the Linux Kernel:

the Linux kernel defines the list_head data structure, whose only fields next and prev represent the forward and back pointers of a generic doubly linked list element, respectively. It is important to note, however, that the pointers in a list_head field store the addresses of other list_head fields rather than the addresses of the whole data structures in which the list_head structure is included; see Figure 3-3 (a).

enter image description here

Why do the pointers in a list_head field store the addresses of other list_head fields rather than the addresses of the whole data structures in which the list_head structure is included?

Given a pointer to a list_head object, how can I get the object of a data structure (such as "data structure 1") which contains the list_head object? For example, How can I get the process descriptor from a PID in Linux kernel?

If it were in a OO language, is it that the list_head fields would likely be private in the data structures in which the list_head structure is included? So is it more reasonable that the pointers in a list_head field store the addresses of the whole data structures in which the list_head structure is included than the addresses of other list_head fields?

halfer
  • 19,824
  • 17
  • 99
  • 186
Tim
  • 1
  • 141
  • 372
  • 590

2 Answers2

2

Why do the pointers in a list_head field store the addresses of other list_head fields rather than the addresses of the whole data structures in which the list_head structure is included?

Because it is logically right and easier to implement. You don't need to know the type to iterate the list. Also list head is not embedded into any structure. What should it point to when list is empty?

Given a pointer to a list_head object, how can I get the object of a data structure (such as "data structure 1") which contains the list_head object?

Using container_of macro.

Alex Hoppus
  • 3,821
  • 4
  • 28
  • 47
1

list_head stores pointer to next/prev list nodes. One data structure can be placed in more then one list using more then one list_head elements in it. Processing code "knows" which of these elements placed into given list and can restore pointer to data structure from pointer to node using list_entry.

ReAl
  • 1,231
  • 1
  • 8
  • 19