Reputation: 1858
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);
}
}
Upvotes: 0
Views: 1824
Reputation: 17505
Change your first if
branch to this:
if((pid=fork())<0){
perror("forking failed");
exit(0);
}
This will tell you what went wrong.
Upvotes: 3