考虑下面这个与shell典型的互动:
用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。
根据这些思路,和我们前面的学的技术,就可以自己来实现一个shell了。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#define SIZE 256
#define NUM 16
int main()
{
char cmd[SIZE];
const char* cmd_line = "[temp@VM-8-3-centos lesson_15]# ";
while(1){
cmd[0] = 0;
printf("%s",cmd_line);
fgets(cmd,SIZE,stdin);
cmd[strlen(cmd)-1] = '\0';
char *args[NUM];
args[0] = strtok(cmd," ");
int i = 1;
do{
args[i] = strtok(NULL," ");
if(args[i] == NULL){
break;
}
++i;
}while(1);
pid_t id = fork();
if(id < 0){
perror("fork error\n");
continue;
}
if(id == 0){
execvp(args[0],args);
exit(1);
}
int status = 0;
pid_t ret = waitpid(id,&status,0);
if(ret > 0 ){
printf("status exit code : %d\n",(status>>8)&0xff);
}
}
return 0;
}