模仿Linux 下的 shell 实现myshell 了解shell的简单实现机制

实现前准备:

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);
}

实现效果

 

最后 谢谢张老师的指导!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值