포럼 회원으로 등록하신분만 다운로드가 가능합니다. 최대 업로드 가능한 용량은 20MB 입니다.

출처 : http://yebig.tistory.com/tag/Linux

* 이중 연결 리스트
   • list_head라는 자료 구조를 이용하여 구현
   • list_head는 전체 자료 구조가 아닌 list_head 필드의 주소를 저장

사용자 삽입 이미지

Double Linked-llist



   • LIST_HEAD(list_name) : 리스트를 새로 만듬
   • list_add(n,p) : p가 가리키는 요소 다음에 n을 가리키는 요소 삽입
   • list_add_tail(n,h) : 첫번째 요소의 주소인 h로 지정한 리스트의 맨 끝에 n이 가리키는 요소 삽입
   • list_del(p) : p가 가리키는 요소 삭제
   • list_empty(p) : 첫번째 요소의 주소로 지정한 리스트가 비어 있는지 검사
   • list_entry(p, t, f) : 이름이 f고 주소가 p인 list_head 필드를 포함한 t타입 자료 구조의 주소 반환
   • list_for_each(p,h) : 첫번째 요소의 주소 h로 지정한 리스트에 있는 요소를 차례로 검색

* list_head를 사용하는 이유

리눅스 커널 Q&A 게시판 펌
(
http://linux.flyduck.com/cgi-bin/webboard/wwwboard.cgi?db=lkqna&mode=read&num=1587&page=9&ftype=6&fval=&backdepth=1)

>옛날 커널에서는 prev , next를 사용했었는데
>요즘에는 list_head 를 사용하는것같습니다.
>list_head를 사용하는 이유는 무엇인지 궁금합니다.
>prev,next를 쓰는것이 더 직관적이지 않을까요?

2.4 커널에서부터 linked list 구현이 아주 일반화되어서 쉽게 linked list를 만들 수 있는데, list_head는 이 linked list head를 정의하는 자료구조라고 이해하면 될 것 같습니다. list_head만 있으면 linked list를 간단하게 만들 수 있다... 이게 이유라고... :-)

>하나더 물어볼게 있는데요....
>list_for_each_safe 라는 게 list.h에 있던데 주석문을 보니 삭제에 대해서 >보호한다고 되어있습니다.
>그런데 이해가 안되는것이 ... 현재 루프를 돌고있는 item에 대해서만
>삭제에 대해서 안전한것 아닌가요?
>예를들어서, A-B-C-D-E  이런식으로 연결되어있을때
>list_for_each를 쓴다면  C를 순회하는도중에 C가
삭제되면 C->next를 얻을수없게되는데......
>list_for_each_safe를 쓰면 C를 순회하는 도중에 C가 삭제되더라도 C->next에대한 복사본을 유지하고 있으니까 이상이 없다고 이해했는데...맞게 이해한것인가요?
>
>하지만, C를 순회하는 도중에  C와 D가 모두 삭제되었다면 속수무책 아닌지요.
>차라리 깔금하게 스핀록 같은걸로 보호하고 list_for_each를 사용하는게 낫지 않을까요?

list_for_each_safe() 함수가 동작하는 방식은 잘 이해하셨습니다. 그렇다면 이를 사용하는 이유는... 코드에서 "linked list를 검색해서 원하는 것을 발견하면 지운다" 같은 일을 하게 되면 list item을 차례로 보면서 해당하는 것이 있으면 현재 item을 지우게 될 것입니다. 이 경우 다음 item을 찾는데 문제가 없게 만드는 것입니다. list_for_each_safe()는 synchronization을 위한 것이 아닙니다.
list를 traverse할 때 현재 item을 지워도 문제가 없게 하기 위한 것입니다.


* Linux linked list

리눅스 커널에서 쓰는 linked list 의 해더 파일이다.

범용으로 쓰기위해 양방향 연결리스트로 선언했고.

더미로 연리스리스트 head 를 선언하였다.


연결리스트 add 를 하다보면 header와 함께 환영 양방향 연결리스트로 구성이되고

prev , next 로 접근함에 따라 stack 방식/ que 방식의 메모리 접근가능.

for루프로 한쪽방향으로 계속 따라 들어가서 접근방식.


malloc으로 메모리 할당은 안했으므로..

단순 stack 메모리에 잡힐수도, malloc으로 사용자 메모리에 쓸수도 있는것이다.?


del 로 링크리스트 끊는 역할만 하므로 메모리는 약간의 낭비가 있을듯하다.?


list_entry 역할..

list 연결리스트의 주소만 갖고 해당 스트럭쳐의 주소를 반환받을수있다.

(어느 형태의 스트럭쳐든 간단히 연결리스트 구성가능)









리눅스 2.4 버젼의 list.h 의 파일을

윈도우용으로 포팅한 소스파일




#ifndef _LINUX_LIST_H
#define _LINUX_LIST_H

/*
 * Simple doubly linked list implementation.
 *
 * Some of the internal functions ("__xxx") are useful when
 * manipulating whole lists rather than single entries, as
 * sometimes we already know the next/prev entries and we can
 * generate better code by using them directly rather than
 * using the generic single-entry routines.
 */

struct list_head {
        struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name)
        struct list_head name = LIST_HEAD_INIT(name)

#define INIT_LIST_HEAD(ptr) do {
        (ptr)->next = (ptr); (ptr)->prev = (ptr);
} while (0)

/*
 * Insert a new entry between two known consecutive entries.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static  void __list_add(struct list_head *new,
                              struct list_head *prev,
                              struct list_head *next)
{
        next->prev = new;
        new->next = next;
        new->prev = prev;
        prev->next = new;
}

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static  void list_add(struct list_head *new, struct list_head *head)
{
        __list_add(new, head, head->next);
}

/**
 * list_add_tail - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static  void list_add_tail(struct list_head *new, struct list_head *head)
{
       __list_add(new, head->prev, head);
}

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static  void __list_del(struct list_head *prev, struct list_head *next)
{
        next->prev = prev;
        prev->next = next;
}

/**
 * list_del - deletes entry from list.
 * @entry: the element to delete from the list.
 * Note: list_empty on entry does not return true after this, the entry is in an undefined state.
 */
static  void list_del(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
        entry->next = (void *) 0;
        entry->prev = (void *) 0;
}

/**
 * list_del_init - deletes entry from list and reinitialize it.
 * @entry: the element to delete from the list.
 */
static  void list_del_init(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
        INIT_LIST_HEAD(entry);
}

/**
 * list_move - delete from one list and add as another's head
 * @list: the entry to move
 * @head: the head that will precede our entry
 */
static  void list_move(struct list_head *list, struct list_head *head)
{
        __list_del(list->prev, list->next);
        list_add(list, head);
}

/**
 * list_move_tail - delete from one list and add as another's tail
 * @list: the entry to move
 * @head: the head that will follow our entry
 */
static  void list_move_tail(struct list_head *list,
                                  struct list_head *head)
{
       __list_del(list->prev, list->next);
        list_add_tail(list, head);
}

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static  int list_empty(struct list_head *head)
{
        return head->next == head;
}

static  void __list_splice(struct list_head *list,
                                 struct list_head *head)
{
        struct list_head *first = list->next;
        struct list_head *last = list->prev;
        struct list_head *at = head->next;

        first->prev = head;
        head->next = first;

        last->next = at;
        at->prev = last;
}

/**
 * list_splice - join two lists
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 */
static  void list_splice(struct list_head *list, struct list_head *head)
{
        if (!list_empty(list))
                __list_splice(list, head);
}

/**
 * list_splice_init - join two lists and reinitialise the emptied list.
 * @list: the new list to add.
 * @head: the place to add it in the first list.
 *
 * The list at @list is reinitialised
 */
static  void list_splice_init(struct list_head *list,
                                    struct list_head *head)
{
        if (!list_empty(list)) {
                __list_splice(list, head);
                INIT_LIST_HEAD(list);
        }
}

/**
 * list_entry - get the struct for this entry
 * @ptr:        the &struct list_head pointer.
 * @type:       the type of the struct this is embedded in.
 * @member:     the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member)
        ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

/**
 * list_for_each        -       iterate over a list
 * @pos:        the &struct list_head to use as a loop counter.
 * @head:       the head for your list.
 */
#define list_for_each(pos, head)
        for (pos = (head)->next; pos != (head);
                pos = pos->next)
/**
 * list_for_each_prev   -       iterate over a list backwards
 * @pos:        the &struct list_head to use as a loop counter.
 * @head:       the head for your list.
 */
#define list_for_each_prev(pos, head)
        for (pos = (head)->prev; pos != (head);
                pos = pos->prev)
               
/**
 * list_for_each_safe   -       iterate over a list safe against removal of list entry
 * @pos:        the &struct list_head to use as a loop counter.
 * @n:          another &struct list_head to use as temporary storage
 * @head:       the head for your list.
 */
#define list_for_each_safe(pos, n, head)
        for (pos = (head)->next, n = pos->next; pos != (head);
                pos = n, n = pos->next)

/**
 * list_for_each_entry  -       iterate over list of given type
 * @pos:        the type * to use as a loop counter.
 * @head:       the head for your list.
 * @member:     the name of the list_struct within the struct.
 */
#define list_for_each_entry(pos, head, member)                         
        for (pos = list_entry((head)->next, typeof(*pos), member);     
             &pos->member != (head);                                   
             pos = list_entry(pos->member.next, typeof(*pos), member); 
                  

#endif






profile

인생은 연극이고 세상은 무대이다!

이솝 임베디드 포럼 운영 및 비즈니스와 관련된 것 이외에 E-Mail이나 메신저 및 휴대폰 등을 통한 개인적인 질문 및 답변은 받지 않습니다. 문의 사항은 이솝 임베디드 포럼 게시판을 이용해 주시면 감사하겠습니다.

엮인글 :
http://www.aesop.or.kr/index.php?mid=Board_Documents_Linux_Applications&document_srl=35538&act=trackback&key=974
List of Articles
번호 제목 글쓴이 날짜 조회 수sort
93 GIT 사용법 (ProGIT) - 1.4. GIT 설치 JhoonKim 2010-01-11 21208
92 GIT 사용법 (ProGIT) - 1.1. 버전 관리 시스템의 개념 file [6] JhoonKim 2010-01-07 19510
91 GIT 사용법 (ProGIT) - 2.1. GIT 저장소(Repository)의 취득 JhoonKim 2010-01-20 18399
90 Makefile 문법 [3] 김재훈 2009-07-25 17144
89 GIT 사용법 (ProGIT) - 1.5. 최초 GIT의 환경 설정 [3] JhoonKim 2010-01-13 16603
88 GIT 사용법 (ProGIT) - 2.5. 원격 저장소의 사용 방법 [2] JhoonKim 2010-02-04 16060
87 GIT 사용법 (ProGIT) - 2.2. GIT 저장소(Repository)에 기록 file [2] JhoonKim 2010-01-21 16033
» 리눅스 Linked-List 구현 관련 참고 자료 김재훈 2009-07-11 15466
85 GIT 사용법 (ProGIT) - 2.6. 태그(TAGS) 붙이기 [2] JhoonKim 2010-02-09 15136
84 GIT 사용법 (ProGIT) - 2.4. 작업의 취소 [1] JhoonKim 2010-02-03 15113
83 GIT 사용법 (ProGIT) - 1.2. GIT 개발 역사 / 1.3. GIT 기본 ... file [3] JhoonKim 2010-01-10 14794
82 리눅스에서 네트워크 속도 측정 방법 [3] 김재훈 2009-07-04 13609
81 ffmpeg encoding option 고현철 2009-10-01 13409
80 GIT 사용법 (ProGIT) - 2.3. 위탁 이력의 열람 file [1] JhoonKim 2010-02-03 13308
79 uBuntu 8.10 에서의 리눅스 개발 환경 설정 [6] 김재훈 2009-01-29 12618
78 Useful Linux Wireless Commands [1] 김재훈 2009-06-05 11966
77 I.MX Multimedia and Applications Framework 기술자료 ... file [2] 장석원 2009-10-26 11060
76 uBuntu Linux - dash를 bash로 변경하는 방법 김재훈 2009-04-28 10966
75 리눅스 어셈블리 프로그래밍을 하자! [2] : ARM 부트코드와 실전... file [2] 김재훈 2009-08-25 10596
74 oss를 이용한 read, write, read/write program file [2] 고도리 2011-01-25 10531

사용자 로그인