2

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);
    } 
}
P̲̳x͓L̳
  • 3,615
  • 3
  • 29
  • 37
choppy
  • 739
  • 1
  • 12
  • 22
  • The program might exit because of an exception or a crash. Try putting `printf("isExit= %d", (int) isExit);` outside of the while loop and see if something is printed. – sashoalm May 18 '12 at 12:28

2 Answers2

7

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.

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
0

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

Attila
  • 28,265
  • 3
  • 46
  • 55