Here is the code snippet of a prog
************** START **********************
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
int glob_var = 100;
int main(void)
{
int var;
pid_t pid;
var = 200;
printf(“++Before Fork()\n”);
if((pid = fork()) < 0) {
perror(“fork error”);
} else if (pid == 0) {
glob_var++;
var++;
printf(“Within Child = > pid: %d <> Parent pid => %d\n”, getpid(), getppid());
} else {
var–;
glob_var–;
}
printf(“pid = %d, glob_var = %d, var = %d\n”,getpid(), glob_var, var);
exit(0);
}
************** END *******************
and here is the output
******************** OUTPUT START ****************
sudipto$ gcc -Wall -g fork01.c -o fork01
sudipto$ ./fork01
++Before Fork()
pid = 4718, glob_var = 99, var = 199
Within Child = > pid: 4719 <> Parent pid => 4718
pid = 4719, glob_var = 101, var = 201
sudipto$ ./fork01 > temp.out
sudipto$ cat temp.out
++Before Fork()
pid = 4720, glob_var = 99, var = 199
++Before Fork()
Within Child = > pid: 4721 <> Parent pid => 4720
pid = 4721, glob_var = 101, var = 201
sudipto$
******************** OUTPUT END ************************
Question: Why is “++Before Fork()” being printed twice when I read from file? Am i missing something here. Thanks!