how to resolve this strange control flow

Hi all:
i am new to Linux system programming and i have written a little programme to practice my skill,but i saw something usual.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <unistd.h>
#include <stdio.h>
int main(int argc,char* argv[]){
    pid_t pid;
    pid = fork();
    if(pid > 0 ){
        printf("I am the parent of pid = %d\n",pid);
    }else if(pid == 0){
        printf("I am the baby!\n");
    }else if(-1 == pid){
        perror("fork");
    }
    return 0;
}

And the output is:
I am the parent of pid = 2492
I am the baby!

How come the else if is executed?
Thanks in advance !
Yep -- very usual. You forked. Both paths are executed.
Isn't either if or else if is executed ? This really confusing!
BTW, the child process is not a thread,right ?
What fork() does is cause a new *process* to execute in parallel to the one running your program. And the new process ALSO continues running your program. So you have effectively made a cloned copy of your running program. You can detect which copy you are 'in' by examining the return value from the fork() function. Each copy gets a different value.

And no, the child process is not a thread. But it is running concurrently.
Last edited on
fork() literally means FORK - you start with one running program (process) and end up with two.
My understanding is that after fork function,if on successful completion,two processes,parent and the child, which are almost the

same,began to execute statements after line 5 in its own "process space"(should i say that) concurrently?

Am i right? Please point out my mistake if any, thanks in advance!

Last edited on
Yes you are correct. After line 5 is below code.

1
2
3
4
5
6
7
8
if(pid > 0 ){
    printf("I am the parent of pid = %d\n",pid);
}else if(pid == 0){
    printf("I am the baby!\n");
}else if(-1 == pid){
    perror("fork");
}
return 0;


So if it is parent process, then if (pid > 0) is true so "I am the parent of pid = 2492" is printed out.
Then if it is the child process, then else if(pid == 0) is true so "I am the baby!" is printed out.

Usually when we do forking, we would want the parent process to wait for the child process to finish doing what they are doing exit and then the parent process terminates. But of cuz depending on your business requirements, you may not want to follow this common pattern though.
Yes, i know the common practice of fork ,this program solely intends to demonstrate my question,anyway,thank you very much!
Topic archived. No new replies allowed.