实现前准备:
1.读取用户输入的字符串 进行裁切处理 ,裁切时以空格为标志
char *fgets(char *s, int size, FILE *stream); // 从指定的流中读入
Under normal circumstances every UNIX program has three streams opened for it when it starts up, one for input, one for output,and one for printing diagnostic or error messages.
在正常情况下,每个UNIX程序都有三个流 它启动时为它打开,一个用于输入,一个用于输出,一个用于打印诊断或错误消息。
#include <stdio.h>
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
2.
#include <string.h>
char *strtok(char *str, const char *delim);
简单调用实例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[]="ls -l -a";
char *p;
p=strtok(str," ");
printf("%s\n",p);
while((p=strtok(NULL," "))!=NULL)
printf("%s\n",p);
return 0;
}
在裁切 一个字符串时
第一裁切 要传入字符串的首地址 //p=strtok(str," ");
在对这个字符串进行第二次裁切时则可以把首地址赋值为 NULL //p=strtok(NULL," ")
3.fork()
fork - 创建子进程
头文件
#include <unistd.h>
函数原型 pid_t fork(void);
函数的返回值
0 //子进程
-1 出错
>0 父进程
调用实例
加 wait 后
4. wait
wait - await process completion //等待子进程结束
5.
int execvp(const char *file, char *const argv[]);
execvp 功能 替换一个进程的映象
myshell.c
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <string.h>
int main()
{
char buf[100];
char *p[100];
while(1)
{
printf("input:");//从终端输入字符串
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';//去掉回车符并且给最后一位赋值\0
int i=1;
p[0]=strtok(buf," ");// 调用字符串裁剪函数
while((p[i]=strtok(NULL," "))!=NULL)
{
i++;
}
p[i]=NULL;
if(strcmp(*p,"quit")==0)
break;
pid_t pid;
if((pid=fork())<0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid == 0)
{
if(execvp(p[0],p)<0)
{
perror("execvp");
exit(EXIT_FAILURE);
}
}
else
{
wait(NULL);//父进程不能先结束,给子进程收尸
}
}
exit(EXIT_SUCCESS);
}
实现效果