代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
char *argv[8];
int argc = 0;
void do_shell()
{
pid_t pid;
if((pid = fork()) == -1 ){
perror("fork");
exit(EXIT_FAILURE);
}
if(pid == 0){
execvp(argv[0],argv);
perror("execvp");
}else {
int st;
while(wait(&st) != pid);
}
}
void do_parse(char *buf)
{
int start = 0;
int i=0;
argc = 0;
while(buf[i])
{
if(!isspace(buf[i]) && start == 0){
argv[argc++] = buf+i;
start = 1;
}
else if(isspace(buf[i]) && start == 1){
start = 0;
buf[i] = '\0';
}
i++;
}
argv[argc++] = NULL;
}
int main()
{
char buf[1024];
while(1){
printf("myshell> :");
scanf("%[^\n]%*c",buf);
do_parse(buf);
do_shell();
}
}
测试:
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/43096f27e6adb0a1e784397f997a007d.png)
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/653efeb228ad0ecab034e6c022a60d7c.png)