我的学习之旅(15)tty.c

模仿linux tty,建立一个console,通过对console的写操作完成字符的显示。

tty.c源代码:

#include <stdarg.h>
#include <mem.h>
#include <tty.h>
#include <console.h>
#include <system.h>
static  tty_struct_t g_tty_table[MAX_CHANNEL_ID];

void tty_init(void)
{
    int i;
    
    for(i=0;i<MAX_CHANNEL_ID;i++) {
        memset((unsigned char *)&g_tty_table[i], 0x0, sizeof(tty_struct_t));
    }
    g_tty_table[CONSOLE_ID].write = console_write;

}

unsigned char get_char_from_queue(tty_queue_t *q)
{
    unsigned char ch = q->buf[q->tail];
    q->tail = ( q->tail + 1 ) & (TTY_BUF_SIZE-1);

    return ch;
}

void put_char_into_queue(tty_queue_t *q, char ch)
{
    q->buf[q->head] = ch;
    q->head = ( q->head + 1 )&(TTY_BUF_SIZE - 1);

    return;
}
void tty_write(tty_struct_t *tty, char *buf, unsigned int len)
{
    char *up = buf;
    char ch;
    
    if( !tty || !buf  || len == 0 || len > 1024)
        return;

    if( tty->write == NULL ) {
        return;
    }
    
    //入write_q队列
    while(len > 0 && (((tty->write_q.tail-tty->write_q.head-1)&(TTY_BUF_SIZE-1)))) { //保证队列没满
        ch = up[0];
        up++;
        len--;
        tty->write_q.buf[tty->write_q.head] = ch;
        tty->write_q.head = (tty->write_q.head+1) & (TTY_BUF_SIZE-1);
    }

    return tty->write(tty, buf );
    
}

tty_struct_t *get_tty(unsigned int channel_id)
{
    if( channel_id >= MAX_CHANNEL_ID)
        return NULL;

    return &g_tty_table[channel_id];
}

tty.h的源代码:

#ifndef __TTY_H__
#define __TTY_H__

#define TTY_BUF_SIZE 1024
enum {
    CONSOLE_ID= 0,
    MAX_CHANNEL_ID
};

typedef struct tty_queue_s {
	unsigned long data;
	unsigned long head;
	unsigned long tail;
	char buf[TTY_BUF_SIZE];
}tty_queue_t;

typedef struct tty_struct_s {
    tty_queue_t read_q;
    tty_queue_t write_q;
    void (*write)(void *tty, char *buf);
    unsigned int task_id;
}tty_struct_t;

void tty_init(void);
tty_struct_t *get_tty(unsigned int channel_id);
unsigned char get_char_from_queue(tty_queue_t *q);
#endif



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值