Linux的shell模拟实现

shell的简单实现

代码部分

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

int main()
{

    while(1)
    {
        printf("[myshell@myhostNameMaHua test]#");
        fflush(stdout);

        char buf[1024];
        ssize_t s=read(0,buf,sizeof(buf)-1);
        if(s>0)
        {
            buf[ s-1 ]=0;
            printf("%s\n",buf);   
        }
        char *_argv[32];
        _argv[0] = buf;
        int i = 1;
        char *start = buf;
        while(*start)
        {
            if(*start ==' ')
            {
                *start = 0;
                start++;
                _argv[i++] = start;
            }
            else
            {
                start++;
            }
        }
        _argv[i] = NULL;
        //eg: ls -a -i -l -n
        pid_t id = fork();
        if(id < 0)   
         {
            printf("creat process fail!\n");
            exit(-1);
        }
        if(id==0)
        {//child
            execvp(_argv[0], _argv);
            exit(1);
        }
        else
        {
            //father
            int status = 0;
            pid_t ret = waitpid(id, &status, 0);
           if( ret > 0)//ret>0 show:successful
           {
               if(WIFEXITED(status))
//exitCode>0 show:result is not right but run is successful
//exitCode==0 show:result is right and run is successful
               {
                   printf("exitCode: %d\n",WEXITSTATUS(status));
               }
               else  
                {
                   printf("child quit by sig!\n");
               }
           }
        }
    }
return 0;
}                                 

实现效果

Linux的shell模拟实现_第1张图片

Linux的shell模拟实现_第2张图片

有待完善,(并没有实现shell的重定向功能)

你可能感兴趣的:(Linux系统编程)