简单shell的实现

#include 
#include
#include

void Run(char *buf,char *argv[]){
  while(1){ 
    printf("myshell:>"); 
    int argc = 0;
    //1.获取命令行 
    gets(buf); 
    //2.解析命令行
    argv[argc] = strtok(buf," "); 
    while(argv[argc]){ 
      argv[++argc] = strtok(NULL," "); 
    }
    //3.建立一个子进程(fork) 
    //4.替换子进程(execvp)
    //5.父进程等待子进程退出(wait)

    pid_t id = fork(); 
    if(id < 0){ 
      perror("fork"); 
    }else if(id == 0){ 
      //子进程 
      execvp(argv[0],argv); 
      perror("execvp");
    }else{ 
      //父进程 
      wait(NULL); 
    } 
  } 
} 

int main(){ 
  char buf[1024] = {0}; 
  char *argv[8] = {NULL}; 
  Run(buf,argv); 
  return 0; 
} 

结果:

[DELL@localhost lesson3]$ ./shell
myshell:>ls -a
.   Makefile         shell    shell.i  shell.s
..  process_creat.c  shell.c  shell.o
myshell:>pwd
/home/DELL/work/lesson3
myshell:>

你可能感兴趣的:(Linux初级)