1.将前面所学的东西融合起来写一个shell ——可以更好的理解啥叫shell
2.以我现阶段的能力只能模拟实现部分
//写一个简单的shell
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
#define NUM 1024
#define SIZE 321
//保存完整的命令行字符串
char cmd_line[NUM];
//保存打散之后的命令行字符串
char* g_argv[SIZE];
//shell运行原理:通过让子进程执行命令,父进程等待&&解析命令;
int main()
{
//命令行解释器,一定是一个常驻内存的进程,不退出
while (1)
{
//1.打印出提示信息[qk1@local host myshell]#
printf("[root@local host myshell]#");
fflush(stdout);
memset(cmd_line, '\0', sizeof(cmd_line));
//2.获取用户的输入和选项:"ls -a -l -i"
if (fgets(cmd_line,sizeof cmd_line, stdin) == NULL)
{
continue;
}
cmd_line[strlen(cmd_line - 1)] = '\0';
//3.命令行字符串解析
g_argv[0] = strtok(cmd_line, " ");//第一次调用,要传入原始字符串
int index = 1;
if (strcmp(g_argv[0], "ls") == 0)
{
g_argv[index++] = "--color=auto";
}
while (g_argv[index++] = strtok(NULL, " "));
//for debug
/* for (index = 0; g_argv[index]; index++)
{
printf("g_argv[%d]:%s\n", index, g_argv[index]);
}*/
//4.to do .内置命令,让父进程shell自己执行的命令,我们叫内置命令,也叫内建命令
//内建命令的本质其实就是shell中的一个函数调用;
if (strcmp(g_argv[0], "cd") == 0)
{
if (g_argv[1] != NULL) chdir(g_argv[1]);//cd path. cd ..
continue;
}
//5.fork()
pid_t id = fork();
if (id == 0)//子进程
{
printf("功能让子进程进行的\n");
execvp(g_argv[0],g_argv);
exit(1);
}
int status = 0;
pid_t ret = waitpid(id,&status,NULL);
if (ret > 0)printf("exit code:%d\n", WEXITSTATUS(status));
}
return 0;
}
标签:实战,index,shell,cmd,argv,LInux,line,include
From: https://blog.csdn.net/qincjun/article/details/139564402