Chinaunix首页 | 论坛 | 博客
  • 博客访问: 128024
  • 博文数量: 30
  • 博客积分: 972
  • 博客等级: 中士
  • 技术积分: 332
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-08 10:04
文章分类

全部博文(30)

文章存档

2012年(30)

分类:

2012-06-17 07:05:27

原文地址:shell外部命令解析器 作者:qizheguang

/* ************************************************************************
 *       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;
}


 

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