Linux下简单的shell实现

78 阅读1分钟

具体步骤:

1.创建一个Makefile

myshell:myshell.c
  gcc -o $@ $^ -g   
.PHONT:clean
clean:
  rm -f myshell

2.创建myshell.c 具体代码如下

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

#define LEN 1024
#define NUM 64
int main()
{
  char cmd[LEN];	
  char *myarg[NUM];		//用于存储分割后的命令
  while(1)
  { 
    printf("[teg@test-centos test]# ");//自己修改后的用户
    fgets(cmd,LEN,stdin);	//获取用户从标准输入流(键盘)输入的命令存储在cmd数组中
    cmd[strlen(cmd)-1] = '\0';//用户在输入后会敲回车 手动置最后一个字符为\0
    int i = 0;
    myarg[i++] = strtok(cmd," ");//把用户输入的字符串用空格分隔开
    while(myarg[i] = strtok(NULL," "))
    {
      i++;
    }
    pid_t id = fork();	//利用fork函数创建子进程
    if(id == 0)			//子进程
    {    
      execvp(myarg[0],myarg);//进程替换
      //int execvp(const char *file, char *const argv[]);
      //函数会从PATH中查找符合第一个参数的目录并执行
      //第二个参数中保存完整的命令
      exit(6);		
    }
	//父进程
    int status = 0;
    pid_t ret = waitpid(id,&status,0);
    //第一个参数为子进程pid
    //第三个参数0表示父进程阻塞等待
    if(ret > 0)
    {
      //等待成功查看进程退出码
      printf("exit code: %d\n",WEXITSTATUS(status));
    }
  }
  return 0;
}                                                 

操作示例:

文件如下所示

shell1.png

make编译文件

shell2.png

运行程序

shell3.png

执行简单命令

shell4.png

新建目录

shell5.png

结束shell可以ctrl + c ,在使用Backspace时需要+ctrl。