I am creating a simple Unix shell in C. I use the fork() to clone the process and exec to execute a new one. It works fine when you are inputting data for the first time in the shell. But when it comes the second iteration fork returns -1.
e.g
…>ls -l /
/results here/
…>ls -l /
forking failed
here is a part of the code:
int execute(char path[80],char *args[]){
pid_t pid;
if((pid=fork())<0){
printf("forking failed"); // The forking failed due to Cannot allocate memory error
exit(0);
}else if(pid==0){
execv(path,args);
}else{
wait(NULL);
}
return 0
}
where path is “bin/ls” and args “ls”,NULL
the main is looks like
int main(){
while(1){
//read from keyboard
//find the program path
//fill args
execute(path,args);
}
}
Change your first
ifbranch to this:This will tell you what went wrong.