Nicole Grefder
Nicole Grefder

Reputation: 3

Strange execlp behavior

I can't understand why the exec in the parent process print after the child functions.

For example, see this code:

if(fork()) {
     // parent
     execlp("ls", "ls", "-l", 0);
     exit(0);
} else {
    // child
    printf("\nChild stuffs...\n");
}

Output:

Child stuffs
..................
... ls command ...

Why "Child stuffs" is being printed before the exec? I don't have wait() or something similar and just can't figure it out...

Every ideas are greatly appreciated :)

Upvotes: 0

Views: 74

Answers (1)

user4815162342
user4815162342

Reputation: 154886

There is no guarantee in which order the operating system scheduler will run the child and the parent process, which have equal priority. In your case one can suspect that the child output is printed first because it takes some time to execute an external program, whereas the printf is executed (and flushed, if line buffered) almost immediately.

If you move the execlp to the child, I would expect the parent to be more likely to display output first.

Upvotes: 1

Related Questions