problem in using fork

Hello everyone!
I just started to learn Linux programming,My doubt may seem very silly to you,but i am really very confused,so help me to get through this-
here goes the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"

using namespace std;

int main(){
	int a=-5;
	switch(a=fork()){
		case -1:
			cout<<"error\n";
			break;
		case 0:
			cout<<"here comes the child\n";
			break;
		default:			
			cout<<"a is "<<a<<endl;
//		break;
	}
	return 0;
}


output:
a is 28866
here comes the child


Question1:I don't understand why both case 0: and default: gets executed !
Question2:According to me value of a should be 0 if child process is created successfully!
fork() creates a child process, that is mostly identical to the parent process and executes from the same place.

As they both execute from the same place, the only way to tell them apart in code is to test the return value from fork().

The child drops into case 0 and writes here comes the child, and the parent drops into the default case and writes the child's pid. As both programs are writing to stdout, you see both texts on the terminal.

BTW, the order of the lines is not deterministic as it's the scheduler that ultimately determines which process gets CPU time first.
Last edited on
thank you very much! Now this is clear, I gone through whole documentation of fork()
http://man7.org/linux/man-pages/man2/fork.2.html
Topic archived. No new replies allowed.