Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1096466
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类: LINUX

2008-04-02 21:45:03

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUFFSIZE 4096
#define ALIGN (sizeof(unsigned long) - 1)

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

struct data_item {
        struct data_item *prev;
        struct data_item *next;
        unsigned int dlen;
        char data[0];
};

static struct list_head head = {
        .prev = (struct data_item *) &head,
        .next = (struct data_item *) &head,
};

static void item_enqueue_tail(struct list_head *head, struct data_item *item)
{
        struct data_item *prev, *next;

        next = (struct data_item *) head;
        prev = next->prev;
        item->prev = prev;
        item->next = next;
        next->prev = prev->next = item;
}

static struct data_item * item_dequeue_head(struct list_head *head)
{
        struct data_item *prev, *next, *result = NULL;

        prev = (struct data_item *) head;
        next = prev->next;
        if (prev == next)
                goto out;

        result = next;
        next = next->next;
        prev->next = next;
        next->prev = prev;
        result->prev = result->next = NULL;
out:
        return result;
}

static struct data_item * item_alloc(ssize_t dlen)
{
        struct data_item *item = NULL;
        ssize_t len;

        len = (sizeof(struct data_item) + dlen + ALIGN) & ~ALIGN;
        item = (struct data_item *) malloc(len);
        if (item) {
                memset(item, '\0', len);
                item->dlen = dlen;
        }

        return item;
}

static void travel(struct list_head *head)
{
        struct data_item *item = NULL;

        while ((item = item_dequeue_head(head)) != NULL) {
                write(STDOUT_FILENO, item->data, item->dlen);
                free(item);
        }
}

int main(void)
{
        char buf[BUFFSIZE];
        ssize_t len;
        struct data_item *item = NULL;

        for (;;) {
                memset(buf, '\0', sizeof(buf));
                len = read(STDIN_FILENO, buf, sizeof(buf));
                if (len <= 0)
                        break;

                item = item_alloc(len);
                if (item)
                        item_enqueue_tail(&head, item);
        }

        travel(&head);

        return 0;
}

阅读(1090) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~