写一个简单的shell命令解释器

/*************************************************************************
#	> File Name: myshell.c
# Author: HuoZG
# mail:248786797@qq.com
# Created Time: Thu 23 Feb 2017 05:23:22 AM PST
 ************************************************************************/

#include<stdio.h>
#include<ctype.h> // isspace()
#include<stdlib.h> // exit()  fflush();
#include<sys/wait.h> // waitpid()
#include<unistd.h> // execvp // 需要 argv  和 命令 不需要  

int main()
{
	char buf[128]; // save input
	while(1)
	{
		char path[100];
	
		gethostname(path, sizeof(path));
		printf("[test@%s ~]$", path);
		fflush(stdout);
		ssize_t _s = read(0, buf, sizeof(buf)-1);	
		if(_s >0)
		{// read sucess
			buf[_s-1] = '\0';
		}
		else
		{// read failed
			printf("read!\n");
			return 1;
		}
		
		char* myargv[32];// get command
		myargv[0] = buf;
		int index = 1;
		char* start = buf;
		while(*start)
		{
			if(isspace(*start))
			{
				*start = '\0';
				start++;
				myargv[index] = start;
				index++;
			}
			else
			{
				start++;
			}
		}


		myargv[index] = NULL;
		pid_t id = fork();
		if(id < 0 )
		{
			printf("create failed\n");
			return 2;
		}
		else if(id == 0)
		{//child
			execvp(myargv[0], myargv);
			printf("command not found\n");
			return 3;
		}
		else
		{// father
			int status = 0;
			ssize_t ret = waitpid(id, &status, 0);					
			if(ret > 0 && WIFEXITED(status))
			{
				//printf("wait sucess ;status:%d \n", WEXITSTATUS(status));
			}
			else
			{
				perror("waitpid");
			}
		}
	}
	return 0;
}


目前只可以实现一些基本的命令。因为还在学习,只写一个最最最原始的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值