C语言,用数组实现stack,用stack实现pipe

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

#define TRUE  1
#define FALSE 0

#define STACK_SIZE 1024

typedef int bool;

struct istack{
    unsigned int top;
    unsigned int bottom;
    unsigned int alloc;
    void *ptr[STACK_SIZE];
};

struct ipipe{
    struct istack s1;
    struct istack s2;
};

void init_stack(struct istack *s)
{
    if (NULL == s)
        return;

    s->alloc = STACK_SIZE;
    s->top = s->bottom = 0;

    memset(s->ptr, 0, STACK_SIZE * sizeof(void *));
}

bool push_stack(struct istack *s, void *v, int size)
{
    void *ptr;

    if (NULL == v || size <= 0)
        return FALSE;

    if (s->top >= s->alloc) 
    {
        printf("stack is full\n");
        return FALSE;
    }

    ptr = (void *)malloc(size); 
    if (ptr){
        memcpy(ptr, v, size);
        s->ptr[s->top++] = ptr;
        return TRUE;
    }
    return FALSE;
}

bool pop_stack(struct istack *s, void *v, int size)
{
    if (NULL == v || size <= 0)
        return FALSE;

    if (s->top == s->bottom) 
    {
        printf("stack is empty\n");
        return FALSE;
    }

    memcpy(v, s->ptr[--s->top], size);

    free(s->ptr[s->top]);
    s->ptr[s->top] = NULL;
    return TRUE;
}

void init_pipe(struct ipipe *p)
{
    if (NULL == p)
        return;
 
    init_stack(&p->s1);
    init_stack(&p->s2);
}


bool write_pipe(struct ipipe *p, int *v)
{
    if (NULL == p || NULL == v) 
        return FALSE;

    if (push_stack(&p->s1, v, sizeof(int)))
        return TRUE;

    return FALSE; 
}

bool read_pipe(struct ipipe *p, int *v)
{
    int tmp;

    if (NULL == p || NULL == v) 
        return FALSE;

    if (pop_stack(&p->s2, v, sizeof(int)))
        return TRUE;

    while(pop_stack(&p->s1, &tmp, sizeof(int)))
        push_stack(&p->s2, &tmp, sizeof(int));

    if (pop_stack(&p->s2, v, sizeof(int)))
        return TRUE;

    return FALSE;
}

int main()
{
    int a = 10;
    char str1[] = "test";
    double b = 1.23;

    int c;
    double g;
    char str2[12];

    int p1;
    int p2;
    
    struct istack s;
    struct ipipe p;

    init_stack(&s);

    /* lock is required in multiple thread programming,
       when push or pop.
     */
    push_stack(&s, &a, sizeof(a));  
    push_stack(&s, str1, sizeof(str1));
    push_stack(&s, &b, sizeof(b));

    pop_stack(&s, &g, sizeof(g));
    pop_stack(&s, str2, sizeof(str2));
    pop_stack(&s, &c, sizeof(c));

    printf("%d, %f, %s\n", c, g, str2);

    init_pipe(&p);

    a = 112;
    c = 11;
    write_pipe(&p, &a);
    write_pipe(&p, &c);
    read_pipe(&p, &p1);

    write_pipe(&p, &c);
    read_pipe(&p, &p2);

    printf("%d, %d\n", p1, p2);
}

猜你喜欢

转载自blog.csdn.net/somyjun/article/details/81356221