How can two conditions work in an if-ifelse-else statement?

My professor shows the following example in C:

#include <sys/types.h> #include <stdio.h> #include <unistd.h> int main() { pid_t pid; /* fork another process */ pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); return 1; } else if (pid == 0) { /* child process */ execlp("/bin/ls", "ls", NULL); } else { /* parent process */ /* parent will wait for the child */ wait (NULL); printf("Child Completed its execution\n"); } return 0; } 

I compiled it and ran it. I saw weird behavior in this code:

The result of the ls' command / command is printed, which is in the else if condition, but also the printed line is "Child Completed its execution \ n", which is in another place.

Isn't that weird behavior?

+4
source share
2 answers

No, you branched it. Two processes are performed. One reported ls and the other reported printf ().

In particular, the process child / forked / bin / ls and the parent called printf () are executed, the output you see.

+5
source

This is because fork creates a child process that continues to run from the same point in the code, but with pid set to 0. What you saw is the parent process executing the printf line, and the child process was executing the ls .

+2
source

All Articles