// 可以在一行输入命令
#include <stdio.h>
#include <string.h>#include <stdlib.h>
#include <ctype.h>
#include <signal.h>
#define STRLEN 50
#define ARGNUM 20
char** Split(char *str){ // 拆分字符串,将输入的字符串拆分成一个一个单词
int szLen = strlen(str);
int ipos = 0,i = 0, wordlen;
int argnum = 0;
char wordBuf[STRLEN+1];
char **argbuf = (char**)calloc(sizeof(char*),ARGNUM);
while(isspace(str[ipos])) ipos++;
i = 0,wordlen = 0;
for(i=ipos; i<szLen; i++){
if(isspace(str[i])){
if(wordlen>0){
wordBuf[wordlen]='\0';
argbuf[argnum]=(char*)calloc(sizeof(char),strlen(wordBuf)+1);
strcpy(argbuf[argnum],wordBuf);
argnum++;
}
wordlen = 0;
continue;
}
else if(isprint(str[i])){
wordBuf[wordlen]=str[i];
wordlen++;
}
}
return argbuf;
}
void execute(char **arglist){ // 处理命令
int pid = fork();
int status;
switch(pid){
case -1:perror("fork fail");
exit(1);
case 0:execvp(arglist[0],arglist);
perror("execvp fail");
exit(1);
default:while(wait(&status) != pid) ;
printf("child exited with state %d,%d\n",status>>8,status&0733);
break;
}
}
int getlistlen(char **arglist){ // 获取命令长度,作为结束的标志
int len = 0;
for(len=0;;len++)
if(arglist[len] == NULL) break;
return len;
}
void setup(){
signal(SIGINT,SIG_IGN);
signal(SIGQUIT,SIG_IGN);
}
int main(){
while(1){
setup();
char strbuf[STRLEN+1];
char **arglist = (char**)calloc(sizeof(char*),ARGNUM);
int arglen = 0;
printf("input a your operate in one line:\n");
fgets(strbuf,STRLEN,stdin);
fflush(stdin);
arglist = Split(strbuf);
arglen = getlistlen(arglist);
if(arglen)
execute(arglist);
else break;
printf("\n");
}
return 0;
}
// 没有完成: 让shell不被用户按下的中断或退出键杀死!