我为我的操作系统课程编写了这个 shell,由于某种原因,当我键入“exit”时,我的 main 函数没有终止,它应该从 while 循环中中断,然后返回 0 到 main,这应该结束程序,但是相反,它只是继续前进。
事实上,它会告诉我它“即将退出”,然后它会返回到 while 循环,并像往常一样继续运行。
有人看到问题了吗?谢谢你的帮助
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define LENGTH 1000
#define MAXCMD 11
void init(char *temp);
void clean(char **orderedIds);
int main (int argc, char *argv[], char *envp[])
{
char temp[LENGTH];
char * tok;
char c = '\0';
int *ret_status;
pid_t pid;
printf("\n$");
int i, j = 0;
while(c !=EOF)
{
//while not ^D // Source: LinuxGazzette Ramankutty
c = getchar();
if(c=='\n')
{ //enter command
char **orderedIds = malloc(MAXCMD * sizeof(char*));
for (i=0; i<MAXCMD; i++)
{
orderedIds[i] = malloc(MAXCMD * sizeof(char*));
}
int k=0;
tok = strtok(temp, " ");
while (tok !=NULL)
{
strcpy(orderedIds[k], tok);
k++;
tok = strtok (NULL, " ");
}
orderedIds[k] = NULL; //END with NULL
init(temp); //initialize the array
pid = fork();
if (pid != 0)
{
//printf("Waiting for child (%d)\n", pid);
pid = wait(ret_status);
}
else
{
if (strcmp(orderedIds[0],"exit")==0)
{ //check for exit
printf("Thank you, now exiting\n");
break;
}
if (execvp(orderedIds[0], orderedIds))
{
printf("%s\n", orderedIds[0]);
puts(strerror(errno));
exit(127);
}
}
clean(orderedIds);
printf("%s", &c);
printf("$ ");
}
else
{
strncat(temp, &c, 1);
}
}
printf("\n I'm a bout to exit!");
return 0;
exit(0);
}
void init(char *temp)
{
//Function to initialize/rest=et the array
int i;
for(i=0; i<LENGTH; i++)
{
temp[i] = 0;
}
}
void clean(char **orderedIds)
{
//garbage collection
int i;
for(i=0; i<MAXCMD; i++)
{
free(orderedIds[i]);
}
free(orderedIds);
}