您的位置:首页 > 运维架构 > Shell

编写一个简易的shell

2018-04-06 14:53 281 查看

下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。



循环过程如下:
1.获取命令行
2.解析命令行
3.建立一个子进程(fork)
4.替换子进程(execvp)
5.父进程等待子进程退出(wait)#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *argv[8];
int argc = 0;

void do_parse(char* buf)
{
int i;
int status = 0;

for(argc=i=0;buf[i];i++)
{
if(!isspace(buf[i])&&status == 0)
{
argv[argc++] = buf+i;
status = 1;
}
else if(isspace(buf[i]))
{
status = 0;
buf[i] = 0;
}
}
argv[argc] = NULL;
}

void do_execute(void)
{
pid_t pid = fork();
switch(pid)
{
case -1:
perror("fork");
exit(EXIT_FAILURE);
break;
case 0:
execvp(argv[0],argv);
perror("execvp");
exit(EXIT_FAILURE);
default:
{
int st;
while(wait(&st) != pid)
;
}
}
}

int main(void)
{
char buf[1024] = {};
while(1)
{
printf("[fabiana@ myshell >]$ ");
scanf("%[^\n]%*c",buf);
do_parse(buf);
do_execute();
}
}运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: