Chinaunix首页 | 论坛 | 博客
  • 博客访问: 577340
  • 博文数量: 136
  • 博客积分: 893
  • 博客等级: 中士
  • 技术积分: 1001
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-31 09:18
个人简介

生命可以终止,梦想不会!

文章分类

全部博文(136)

文章存档

2016年(4)

2015年(2)

2014年(5)

2013年(7)

2012年(118)

分类: LINUX

2012-04-08 13:55:59

/* ************************************************************************
 *       Filename:  shell.c
 *    Description: 
 *        Version:  1.0
 *        Created:  2012年04月02日 18时52分12秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (),
 *        Company: 
 * ************************************************************************/

于2012年04月09日修改后的代码:

#include
#include
#include
#include
#include
#include

int main(int argc,char *argv[])
{
 while(1)
 {
  pid_t pid;
  char *p1=NULL,*p2=NULL,*p3=NULL;  //指针要初始化
  char *p4=NULL;
  char str[100]="";  //这里要初始化或者用memset函数初始化
  char *temp[100];
  int i=0;
  int status;
 
  p1=getenv("USER"); //取得环境变量内容getenv()
  p2=getenv("HOSTNAME");
  p3=getenv("PWD");
  p4=strrchr(p3,'/');
  printf("[%s@%s %s]$",p1,p2,p4+1);
//  gets(str);
/*可以代替下面的4句话
  fgets(str, sizeof(str), stdin);//获取字符串
  str[strlen(str)-1]='\0';   //把最后一位'\n'变成字符串结束标志'\0'
  if(str[0]=='\0')
   continue;    //如果是输入回车的话,继续while循环
  temp[i++]=strtok(str, " ");
  while((temp[i++]=strtok(NULL," "))!=NULL);   //字符串按空格切割      
*/
  fgets(str,100,stdin);  //str用指针时要开辟空间,100可以用strlen测出str的长度来代替
  temp[i++]=strtok(str," \n"); 
  while((temp[i++]=strtok(NULL," \n"))!=NULL)
  ;
  pid=vfork();
  if(pid<0)
  {
     perror("fork\n");
  }
  else if(pid==0)
  {    
     if(temp[0]==NULL)
     {
        exit(0);
     } 
        execvp(temp[0],temp);
  }
  else
  {
      pid=wait(&status);
  }
 
 }
 return 0;
}


 

阅读(2185) | 评论(6) | 转发(1) |
给主人留下些什么吧!~~

qizheguang2012-06-18 08:48:25

hclen90615: 会有两个问题:1、strrchr参数2类型未转换。2、在无法识别的外部命令时应该打印错误提示。.....
谢谢提醒哈,

hclen906152012-06-17 07:13:50

会有两个问题:1、strrchr参数2类型未转换。2、在无法识别的外部命令时应该打印错误提示。

hclen906152012-06-17 07:06:46

正巧,前天也写了一个•••

qizheguang2012-04-10 07:58:34

☆彼岸★花开: 不太长啊…….....
它只是实现了shell脚本外部的一些简单的命令,这个好像不需要太长吧..

☆彼岸★花开2012-04-10 01:47:00

不太长啊……