Chinaunix首页 | 论坛 | 博客
  • 博客访问: 574976
  • 博文数量: 99
  • 博客积分: 3976
  • 博客等级: 中校
  • 技术积分: 1041
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-15 15:48
文章分类
文章存档

2009年(1)

2008年(5)

2007年(31)

2006年(58)

2005年(4)

分类: C/C++

2007-03-06 19:40:15

/********************************************************************

name: simple shell(shk.c)
written by: 1jjk
E-mail: lingjiujianke@gmail.com
compile: [ljjk @ljjk ljjk]#gcc -O2 -Wall -o shk shk.c
for example: [ljjk @ljjk ljjk]#./shk1
>/bin/ls
shk.c shk
>Ctrl+c
>
********************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>
#include<signal.h>

#define MAX 128

void evl(char *cmdlin);
int parse(char *cmdline, char **argv);
int build(char **argv);

char *Fgets(char *ptr,int n, FILE *fp)
{
    char *rptr;
    if(((rptr=fgets(ptr,n,fp))==NULL)&&ferror(fp))
    {
        printf("fgets error\r\n");
    }
    return rptr;
    
}

int main(int argc,char **argv, char **env)
{

    char cmd[MAX];
    while(1){
        fprintf(stdout,"> ");
    if(signal(SIGINT,main)==SIG_ERR)
    fprintf(stdout,"signal error\r\n");
    Fgets(cmd,MAX,stdin);
    if(feof(stdin))
        {
            exit(0);
        }
        evl(cmd);
        
    }
}

void evl(char *cmdline)
{
    char *argv[MAX];
    int bg;
    pid_t pid=0;
    bg=parse(cmdline,argv);
    if(argv[0]==NULL)
        return ;
    if(!build(argv))
    {
        if((pid=fork())==0)
            if(execve(argv[0],argv,NULL)<0)
            {
                fprintf(stdout,"%s command not found.\r\n",argv[0]);
                exit(0);
            }
    }
    if(!bg)
    {
        int sta;
        if(waitpid(pid, &sta,0)<0)
        {
            fprintf(stderr,"waitpid error\r\n");
        }
        else
        {
            fprintf(stdout,"%d %s",pid,cmdline);
        }
    }
    return;
}

int build(char **argv)
{
    if(!strcmp(argv[0], "quit")||!strcmp(argv[0],"exit"))
        exit(0);
    if(!strcmp(argv[0], "&"))
        return 1;
    if(!strcmp(argv[0], "ls"))
        fprintf(stdout,"sssss\n");
    return 0;
}

int parse(char *buf, char **arv)
{
    char *delim=NULL;
    int arg,bg;
    //char *buf=NULL;

    buf[strlen(buf)-1]=' ';
    
    while(*buf&&(*buf==' '))
        buf++;
    arg=0;
    while((delim = strchr(buf, ' ')))
    {
        arv[arg++]=buf;
        *delim='\0';
        buf=delim+1;
        while(*buf&&(*buf==' '))
            buf++;
    }
    arv[arg++]=NULL;
    if(arg==0)
        return 1;

    if((bg=(arv[arg-1]=='&'))!=0)
        arv[--arg]=NULL;

    return bg;
        
}

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