Lab2_Simple Shell_xv6_2019

Lab2: 实验目的:学习unix的shell如何使用系统调用

一. 实验准备

Your job is to write a simple shell for xv6. It should be able to run commands with arguments, handle input and output redirection, and set up two-element pipelines. Your shell should act like the xv6 shell sh for these examples as well as similar commands:
我需要写一个简单的shell,它要支持运行带参数的命令,输入输出重定向,设置两个管道;我的shell 应该支持那些指令,那么面向测试程序编程,可以看看testsh.c中t1~t9函数,一共有9条,详见:user/testsh.c
提示:

  • 我的shell应该写在user/nsh.c下,然后在makefile里添加它并编译;

  • 我的shell应以@开头而不是$,方便和xv6shell区分开;运行效果像下面这样:

  • 不要使用内存分配器函数,如malloc();尽量使用栈内存和全局变量;

  • 可以限制cmd名字的长度,参数的数量,和单个参数的长度等;

  • 可以使用testsh测试你的nsh.c;testsh会将输出重定向,你也可以修改testsh的代码,方便你看到自己程序的输出;

  • 大佬c语言书里的代码时很有用的,多看看,如5.12节的gettoken(); 这个函数sh.c有用到

  • 参考资料:这里可以参考哈工大的实验链接,它也是用的mit 6.s081的课程,https://hitsz-lab.gitee.io/os_lab/lab2/part3/,可以把它当成中文版的翻译;

二. 知识点

  1. int unlink(const char*);函数,关闭给定文件的所有文件描述符的链接,然后删除文件;如果给定的是一个文件的软链接,则删除这个软链接
  2. int chdir(const char*);是C语言中的一个系统调用函数(同cd),用于改变当前工作目录,其参数为Path 目标目录,可以是绝对目录或相对目录。
  3. gets(char *buf, int max)从标准输入中读取字符,直到遇到\n\r
  4. fprintf(int fd, const char *fmt, ...) 指定给指定文件描述符fd中写入字符串

三. 任务分解

我自己实现的shell都要完成那些任务

  1. main()函数, shell的main函数不需要参数,它从标准输入中读取数据
int main(void)
{
   
   
	static char buf[100];
	int fd;

	// Ensure that three file descriptors are open.
	while ((fd = open("console", O_RDWR)) >= 0)
	{
   
   
		if (fd >= 3)
		{
   
   
			close(fd);
			break;
		}
	}

	// Read and run input commands.
  // getcmd 从标准输入中读取字符,直到遇到`\n`获`\r`。
	while (getcmd(buf, sizeof(buf)) >= 0)
	{
   
   
		if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){
   
   
		  // Chdir must be called by the parent, not the child.
		  buf[strlen(buf)-1] = 0;  // chop \n
		  if(chdir(buf+3) < 0)
		    fprintf(2, "cannot cd %s\n", buf+3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值