This is a cleaned code that I’m using in order to execute shell commands.
Though isExit is always 0 and loop should run as long as it is !isExit, my program terminates after one loop with the command ls as argument to execute.
Does anyone have any idea?
The output is OK (ls) but then program terminates.
The code is written in C, on Eclipse.
Running on Ubuntu 12 which is running on VM over Windows 7.
int main() {
int numberOfCommands, numOfWords, i, isExit = 0, isBackGround = 0, isSucces;
char input[256];
char *cmdAndArgs[256];
char *commands[256];
do{
// gets and parses user command...
ExecuteCmd(cmdAndArgs);
} while (!isExit);
return EXIT_SUCCESS;
}
void ExecuteCmd(char *cmdAndArgs[]){
pid_t pid;
pid = fork();
if (pid != 0) {
execvp(cmdAndArgs[0], cmdAndArgs);
exit(0);
} else {
waitpid(pid, &status, 0);
}
}
You’re running the execvp in the parent process, not in the child. the logic:
should be reversed to:
the return codes from
fork()are:-1== fork failed (useerrnoto determine the reason).0== I am the child.> 0== I am the parent. See the reference for fork under the RETURN VALUE section.