choppy
choppy

Reputation: 749

unexpected termination of program running in a loop

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);
    } 
}

Upvotes: 2

Views: 240

Answers (2)

Anya Shenanigans
Anya Shenanigans

Reputation: 94624

You're running the execvp in the parent process, not in the child. the logic:

pid_t pid;
pid = fork();
if (pid != 0) {
    execvp(cmdAndArgs[0], cmdAndArgs);
    exit(0);
} else {
    waitpid(pid, &status, 0);
}

should be reversed to:

pid_t pid;
pid = fork();
if (pid == 0) { /* Child */
    execvp(cmdAndArgs[0], cmdAndArgs);
    exit(0);
} else if (pid == -1) {
    perror("fork");
} else {
    waitpid(pid, &status, 0);
}

the return codes from fork() are: -1 == fork failed (use errno to determine the reason). 0 == I am the child. > 0 == I am the parent. See the reference for fork under the RETURN VALUE section.

Upvotes: 7

Attila
Attila

Reputation: 28762

Is it possible that you have a buffer overflow in // gets and parses user command...? If you write past the allocated space, you can end up overwriting the value of isExit

Upvotes: 0

Related Questions