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