Chinaunix首页 | 论坛 | 博客
  • 博客访问: 67657
  • 博文数量: 45
  • 博客积分: 67
  • 博客等级: 民兵
  • 技术积分: 240
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-28 15:43
文章分类
文章存档

2013年(1)

2012年(41)

2011年(3)

我的朋友

分类: LINUX

2012-05-22 15:25:57

#include
#include
#include
#include
#include
#include
#include
#include

char cmd[128];               //the path when opening the shell 
char cmd_buf[256];           //store the parameters
char *cmd_argv[128];         //store the parameters' array subscript

int getfrontdir(char buf[])   //get the front dir
{
    int i,j = 0;
    for ( i = 0 ; buf[i] != '\0' ; i ) {
        if ( buf[i] == '/' ) {
            j = i;
        }
    }

    if ( j == 0)

         j = 1;
    return j;
}

int getdir()   //get the dir
{
    struct passwd *pwd;
    pwd = getpwuid(getuid());
    int i;
    char buf[256];
    if (strcmp(cmd_argv[0],"cd") == 0) {
        getcwd(buf,256);
        if ( cmd_argv[1] == NULL ) {
            strcpy(buf,pwd->pw_dir);
            chdir(buf);
        }
        else {
            if ( strcmp(cmd_argv[1],"..") == 0 ) {
                i = getfrontdir(buf);
                buf[i] = '\0';
                chdir(buf);
            }else {
                strcpy(buf,cmd_argv[1]);
                if ( chdir(buf) == -1 )

                    fprintf(stderr,"%s:%s\n",cmd_argv[0],strerror(errno));
            }
        }
        return 1;
    }else {
        return 0;
   }
}

void FORK()  //make a child pid ,then do the cmd
{
    pid_t pid;

    if ( (pid = vfork()) == -1 ) {
        perror("fork");
        exit(-1);
    }

    if ( pid > 0 ) {
        int i;
        wait(&i);
    }
    else {   
        if ( execvp(cmd_argv[0],cmd_argv) == -1 ) {
            perror("execvp");
            exit(1);
        }
    }
}
void Get() //get the string which is write on the gnome
{
    int c;
    int i = 0, j = 0;
    while ( (c = getchar()) != '\n' ) {
        if ( c == ' ') {
            cmd_buf[i ] = '\0';
        }else {
            if ( cmd_buf[i-1] == '\0' ) {
                cmd_argv[j ] = cmd_buf i;
            }
            cmd_buf[i ]=c;
            cmd_buf[i] = '\0';
        }
    }
    cmd_argv[j] = NULL;

}

void main_loop()  //the main
{
    int i = 0;
    strcpy(cmd,"Myshell:");
    char path[128];
    getcwd(path,128);
    strcat(path,"$ ");
    strcat(cmd,path);
    printf("%s",cmd);
    fflush(stdout);
    Get();
    if ( strcmp(cmd_argv[0],"exit") == 0 ) {
        exit(0);
    }
    else {
        i = getdir();
        if ( i != 1 ) {
            FORK();
        }
    }
    bzero(cmd,128);
}


int main(int argc,char **argv)
{
    while(1) {
        main_loop();
    }
 return 0;
}

    自己写的shell,通过Get()函数来获得shell命令的各个参数并放到cmd_buf中,将参数中的空格换成“\0”并将数组中“\0”下个数的数组下标存放到cmd_argv中,以此来实现将多个参数分离的功能。函数getdir()和getfrontdir(char buf[])是用来实现“cd”命令的。
    此shell通过多进程来实现,每一个命令都会为其创建一个新的进程来使其运行。
阅读(493) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~