在学习完fork、wait、waitpid、exec等函数,我们可以实现一个简单的myshell函数。
来来来,直接上代码。
我们采用的是execvp()程序替换,也就是带环境变量用数组
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
char* argv[8]; //这个数组用来存放执行的命令
int arg = 0;
//下面这个函数用来读取输入的指令并且将指令的地址储存到argv数组里
void do_parse(char* buf){
int i;
int status = 0;
for(arg=i=0; buf[i]; i++){
if(!isspace(buf[i]) && status == 0){
//如果不是空格,且标志位status为0,将下一个元素保存到argv数组中
argv[arg++] = buf + i;
status = 1;
//保存完成之后,将标志位置为1
}else if(isspace(buf[i])){
// 如果是空格,设置标志位status为0
status = 0;
buf[i] = 0;
}
}
argv[arg] = NULL;
//将argv数组的最后一个元素设置为NULL
return;
}
void do_execute(){
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);
//这个是用轮循的方法等待,如果没有等到pid就继续循环,直到等到pid
waitpid(-1,&st,0);
//阻塞式等待
}
}
}
int main(){
char buf[1024] = {};
while(1){
printf("myshell> ");
scanf("%[^\n]%*c",buf);
/*^表示非,读到其后面的字符就停止读入,也就是说空格、
制表符、空的字符不影响读入。而%s只能读取字符串,显然
满足不了要求。%*c表示读入,\n否则后面讲一直读入\n。*/
do_parse(buf);
do_execute();
}
}
上面的内容就是关于用fork实现mysleep()的介绍,由于本人的能力有限,可能在介绍中有些不妥或者bug存在,欢迎发邮件到我的邮箱(Cyrus_wen@163.com)批评指正!