C programming return 0 does not terminate the program
I wrote this wrapper for my operating system course and for some reason my main function doesn't end when I type "exit" it is supposed to break from the while loop and then return 0 in main, which should end but instead it just keeps going.
In fact, he will tell me that his "fight to quit" and then he will return to the while loop where it will work as usual.
Does anyone see the problem? Thank you for your help.
#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);
}
source to share
Well, he's coming out. The problem is you are forcing. You have to be careful what you do. My guess is that if the child process exits, all parent processes are expected to terminate in a chain. You do it:
pid = wait(ret_status);
But never do anything with the result. By the way, just because it wait
expects a pointer doesn't mean you should pass an uninitialized pointer to it. You define:
int *ret_status;
What you should really do is:
int ret_status; pid = wait(&ret_status);
And then check the value ret_status
. If this indicates that you (the parent) should exit, then you should break
.
source to share