Chinaunix首页 | 论坛 | 博客
  • 博客访问: 613331
  • 博文数量: 144
  • 博客积分: 5037
  • 博客等级: 大校
  • 技术积分: 1581
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-30 21:49
文章存档

2010年(16)

2009年(128)

分类: LINUX

2009-04-19 19:23:41

文件: shellprograme0.01.zip
大小: 16KB
下载: 下载

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

int main(void)
{
    char buf[100] = {""};
    char temp[100] = "ls -a -l -n -l"; //简单的历史命令

    struct termios old_opt, opt;
    char ch;
    int i = 0;
    int j = 0;
      
    //printf("this is test!\n");

    tcgetattr(0, &old_opt);
    opt = old_opt;
    
    opt.c_lflag &= ~ECHO;
    opt.c_lflag &= ~ICANON;
    
    tcsetattr(0, TCSANOW, &opt); //设置

    
    printf("[mysh@ localhost shell]>> ");
    while(1)
    {
        ch = getchar();
        if( ch == 27 )
        {
     // printf("test!\n");

            getchar();
            if( (ch = getchar()) == 65 || ch == 66 )
            {
                if(ch == 65) //上键

                {
                    i = strlen(buf);
                    memset(buf, 0, 100);
                    strcpy(buf, temp);
                    printf("\r[mysh@ localhost shell]>> ");
                    for(j = 0; j < i; j++)
                    {
                        printf(" ");//覆盖掉自己

                    }
                    printf("\r[mysh@ localhost shell]>> %s",buf);
                    fflush(stdout);
                }
                else if(ch == 66) //下键

                {
                    i = strlen(buf);
                    strcpy(buf, temp);
                    printf("\r[mysh@ localhost shell]>> ");
                    for(j = 0; j < i; j++)
                    {
                        printf(" ");//覆盖掉自己

                    }
                    printf("\r[mysh@ localhost shell]>> %s", buf);
                    fflush(stdout);
                }
            }
        }
        else if(ch == 127) //删除键的设置

        {
            i = strlen(buf);
            if(i != 0)
            {
                buf[i - 1] = '\0';
                i--;
                printf("\r[mysh@ localhost shell]>> ");
                for(j = 0;( j < i+1); j++)
                {
                    printf(" ");//覆盖掉自己

                }
                fflush(stdout);
                printf("\r[mysh@ localhost shell]>> %s", buf);
                fflush(stdout);
            }
        }
        else if(ch == 10) //enter键获取命令

        {
            break;
        }
        else
        {
            i = strlen(buf);
            printf("%c", ch);
            buf[i] = ch; //命令储存

            i++;
        }
    }
    tcsetattr(0, TCSANOW, &old_opt); //恢复


    printf("\n");
    return 0;
}

用在了我shell命令解释器上了,挺好用,不过 左右键的我没有弄出来(放在了后面的文章中续......)。希望高手指点

小弟先谢了...

后续整理中连接----->后续整理中连接--下篇续linux GNU shell中上下键翻历史的实现--->

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

chinaunix网友2011-07-14 16:00:57

细心点,密码在里面

chinaunix网友2011-06-27 11:40:55

还有密码?