Themis Mavridis
Themis Mavridis

Reputation: 166

Fork and multiprocessing

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
    int p;
    p = fork();
    if (fork()==0) {
        if (execl("/bin/echo", "/bin/echo", "foo", 0) == -1) {
            fork();
        }
        printf("bar\n");
    }
    else {
        if (p!=0) execl("/bin/echo", "/bin/echo", "baz", 0);
        }
}

Why does this program print baz foo foo and not bar foo baz? At p=fork() a child i created.The parent goes to else{} and prints baz. Then in the line if(fork()==0) a grandchild is created. So the grandchild enters and print foo. Should it also print bar?

Upvotes: 0

Views: 284

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The exec* functions replaces the process with the new program, so the code after the execl call you do never runs.

Upvotes: 2

Related Questions