user3217278
user3217278

Reputation: 350

Why doesn't the child execute after the fork()? It never gets to child's part of code.

Here is the code I have. I basically want to create a child process that will execute some commands through execvp(). However the program never reaches there as it never prints "Got to child". I dont understand why. Can someone explain what the error is? Because I think I'm following the procedure to the t.

    pid_t pid;
    pid = fork();

    if (pid < 0) { //if fork() returns less than 1 it failed
        fprintf(stderr, "fork failed");
        return 1;
    }
    else if (pid == 0) {  //for() returns 0 then this is the child process
        printf("Got to child");
        int exec;
        exec = execvp(args[0], args); /* (2) invoke execvp() */
        if (exec < 0) {
            printf("Error: executing command failed.\n");
            exit(1);
        }
    }
    else { //pid>0 therefore this is the parent process
        if (background == 0){
        wait(&status);
        printf("Got to parent");
        }
    }

Upvotes: 1

Views: 1683

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

You don't see Got to child because you don't include a newline at the end of the message. If you add the newline, you'll probably suddenly see the message. If you want to be reasonably sure of seeing the output, use a newline at the end of the message. If you want to be still more sure of doing so, add fflush(stdout); or fflush(0);.

You don't need to test the return value from execvp(). It only ever returns if it is unsuccessful. You should report error messages to standard error, not standard output.

Upvotes: 3

waTeim
waTeim

Reputation: 9225

This looks like the typical pattern but I wonder if

printf("Got to child");

without the \n causes the unwritten buffer to get thrown away when the exec happens and so no output.

Upvotes: 6

Related Questions