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
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"
usingnamespace 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.