??????linux?????????????????????????????
????1?????????????????????????????????????cd??exit??
????2???????????
??????????????????????????????????????????
????1.????????????cd??exit???????????????????????
????2.??????????????????????????????????path?????????в?????????????У????shell?????????????????????
????3.?????????????????&?????????????????????????????????????????????????wait(*status)????????????????????????????????????


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>
#define MAXLEN 80
char cwd[MAXLEN];//?????????
char *prompt;
char* parseCmd(char* cmd?? char** argarr?? int* argc)
{
enum states {S_START?? S_INTOKEN?? S_INQUOTES};
int numArgs = 0;//???????
int loop = 1;//??????
enum states state = S_START;//?????
int lastch;
while(loop)
{
switch(state)
{
case S_START:
if(*cmd == '"')
{
*argarr++ = cmd + 1;
numArgs++;
state = S_INQUOTES;
}
else if(*cmd == 0 || *cmd == ';')
loop = 0;
else if(*cmd <= ' ')//????ascii????е?????????????????
*cmd = 0;
else
{
*argarr++ = cmd;
numArgs++;
state = S_INTOKEN;
}
break;
case S_INTOKEN:
if(*cmd == 0 || *cmd == ';')
loop = 0;
else if(*cmd <= ' ')
{
*cmd = 0;
state = S_START;
}
break;
case S_INQUOTES:
if(*cmd == 0)
loop = 0;
else if(*cmd == '"')
{
*cmd = 0;
state = S_START;
}
break;
}
cmd++;//???????????
}
*argarr = NULL;//?????????????
if(argc != NULL) *argc = numArgs;
lastch = cmd[-1];
cmd[-1] = 0;
return lastch == ';' ? cmd : NULL;// ???????????????????????????????????
}
int main(int argc?? char** argv)
{
char cmd[80];
char* source = NULL;
char* arg[20];
int statval;
int numArgs;
while(1)
{
if(source == NULL)
{
getcwd(cwd??MAXLEN);
printf("%s$ "??cwd);
//???????
if((source = gets(cmd)) == NULL)
exit(0);
}
source = parseCmd(source?? arg?? &numArgs);
if(numArgs == 0) continue;
//??????????
if(strcasecmp(arg[0]?? "exit") == 0)
{
exit(0);//????exit????????в???????????
}
if(!strcmp(arg[0]??"cd"))//?л?????????????
{
chdir(arg[1]);
continue;
}
if(!strcmp(arg[numArgs-1]??"&"))//???????
{
char* a[20];//???????
int k;
for(k=0;k<numArgs-1;k++)
{
a[k] = malloc(strlen(arg[k]) + 1);
strcpy(a[k]??arg[k]);
//printf("%s "?? a[k]);
}
a[k] = NULL;
if(fork() == 0)
{
if(execvp(a[0]??a) == -1)// ??????
fprintf(stderr?? "exec %s failed: %s "??argv[0]??strerror(errno));
exit(1);//????????
}
for(k=0;k<numArgs-1;k++);//??????
free(a[k]);
continue;
}
//????????????????
if(fork() == 0)
{
if(execvp(arg[0]??arg) == -1)// ??????
fprintf(stderr?? "exec %s failed: %s "??argv[0]??strerror(errno));
exit(1);//????????
}
wait(&statval);
}
}