参照元†
- リストの先頭、リストを含む構造体のポインタを取得するマクロ。リストが空ならばNULLを返す。
- struct list_head *ptr
- 構造体内のリスト先頭へのポインタを指定する。
- struct list_head *以外の型を指定してもコンパイルエラーにはならないが、struct list_head *以外の型のポインタから構造体のポインタを求めたい場合はcontainer_of()を使った方が良い。
- linux-5.15/list_head
- type
- ptr に指定したポインタが指すメンバ、これを含む「構造体名」を指定する。マクロはここで指定した型のポインタを返す。
- member
- ptr に指定したポインタが指す「メンバ名」を指定する。
- type に指定した型は member に指定した名前のメンバを持っていないとコンパイルエラーになる。
返り値†
- type *
- 例えばlist_first_entry_or_null(a, struct hogehoge, b)とすれば、struct hogehoge *が返ってくる。
- list_entry()と同じ仕様。
- linux-5.15/list_entry()
/**
* list_first_entry_or_null - get the first element from a list
* @ptr: the list head to take the element from.
* @type: the type of the struct this is embedded in.
* @member: the name of the list_head within the struct.
*
* Note that if the list is empty, it returns NULL.
*/
#define list_first_entry_or_null(ptr, type, member) ({ \
struct list_head *head__ = (ptr); \
- ptrを一度だけ評価するため一旦変数に代入する。マクロの場合は、ptrに副作用がある場合(インクリメントなど)にptrを何度も評価すると、副作用が何度も発生してしまう。
struct list_head *pos__ = READ_ONCE(head__->next); \
pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
})
- nextが自分を指している(つまりリストが空)場合はNULL、そうでなければnextが指している要素(= 先頭の要素)
コメント†