Wednesday, February 10, 2010

CodeByte: OpenBSD Linked Lists

If you are ever doing systems programming on OpenBSD, there are a number of linked list macros pre-defined, which you may find useful. See the manual page for QUEUE(3).

Here is a quick example I knocked up:



#include <stdio.h>
#include <sys/queue.h>
#include <stdlib.h>
#include <string.h>

#define SWM_MAX_ALT_WM_NAME 32

struct alt_wm {
SLIST_ENTRY(alt_wm) entries;
char wm[SWM_MAX_ALT_WM_NAME];
};

int
main(void)
{
struct alt_wm *n1, *n2, *n3, *node;

SLIST_HEAD(head, alt_wm) alt_wms_head;
SLIST_INIT(&alt_wms_head);

n1 = malloc(sizeof(struct alt_wm));
strlcpy(n1->wm, "cwm", SWM_MAX_ALT_WM_NAME);

n2 = malloc(sizeof(struct alt_wm));
strlcpy(n2->wm, "fvwm", SWM_MAX_ALT_WM_NAME);

n3 = malloc(sizeof(struct alt_wm));
strlcpy(n3->wm, "cde", SWM_MAX_ALT_WM_NAME); /* oldskool */

SLIST_INSERT_HEAD(&alt_wms_head, n1, entries);
SLIST_INSERT_HEAD(&alt_wms_head, n2, entries);
SLIST_INSERT_HEAD(&alt_wms_head, n3, entries);

SLIST_FOREACH(node, &alt_wms_head, entries) {
printf("%s\n", node->wm);
}

return(0);
}

2 comments:

Ribalba said...

I wish Linux had a default. I always take my own implementation so I don't depend on something stupid and then everything goes segfault :)

TW Burger said...

Good example. I wrote my on linked list handler to use in any environment. I got tired of not being able to be fully able to trace into all of the code.

Here is the link to the article I wrote for IBM:

http://www.ibm.com/developerworks/linux/library/l-tip-generic.html