写一个自己的shell界面

来源:互联网 发布:最近流行的网络词语 编辑:程序博客网 时间:2024/04/29 13:48
  1 #include <stdio.h>                                                          2 #include <sys/types.h>  3 #include <sys/wait.h>  4 #include <unistd.h>  5 int main()         6 {                  7     while(1)       8     {              9         printf("[myshell@myhostName test]# "); 10         fflush(stdout); 11         char buf[1024]; 12         ssize_t s=read(0, buf, sizeof(buf)-1); 13         if(s > 0) 14         {         15             buf[s-1] = 0; 16             printf("%s\n",buf); 17         }   18         char* _argv[32]; 19         _argv[0] = buf; 20         int i=1; 21         char* start = buf; 22         while(*start) 23         {        24             if(*start == ' ') 25             {    26                 *start = 0; 27                 start++; 28                 _argv[i++] = start; 29             }    30             else 31                 start++;                                                   32         }        33         _argv[i] = NULL; 34         pid_t id = fork(); 35         if(id == 0) 36         {       //child 37             execvp(_argv[0], _argv); 38             exit(1); 39         }        40         else     41         {      //father  42             int status = 0; 43             pid_t ret = waitpid(id, &status, 0); 44             if(ret > 0) 45             {    46                 if(WIFEXITED(status)) 47                 { }                                                        48                 else 49                 { 50                     printf("child, quit by sig\n"); 51                 } 52             } 53         } 54     }        55     return 0; 56 }   

用进程替换函数execvp(),来进行编写。
execvp(const char* file, char* const argv[]);
file—->文件名
argv[]—->可变参数列表,用来存放要进行的操作。
execvp()还有其他五个相同类型的函数,分别是:

       int execl(const char *path, const char *arg, ...);       int execlp(const char *file, const char *arg, ...);       int execle(const char *path, const char *arg,                  ..., char * const envp[]);       int execv(const char *path, char *const argv[]);       int execvp(const char *file, char *const argv[]);       int execve(const char *filename, char *const argv[],                  char *const envp[]);

其中,execve()函数是最底层的函数,其他五个函数都是调用该函数来实现。

0 0
原创粉丝点击