I am studying about fork(), as I learned, in fork(), the parent and child both have same "image" i.e, they both point to the same page table which all its page table entries are marked (when kernel handles the syscall) as read-only. when writing to a page, e.g, updating a variable, an anonymous page is opened, and changes are stored there, hence practically the child and parent don't have an influence on each other's variables. I encountered a strange case where I can't figure out what's going on. the thing I can't figure out is what happens when the returned fork() value ends up in the static variable and when exactly is the split made:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
static int a = 0;
static int r = 0;
int main() {
r = fork();
if (r > 0){
a = 1;
}
if (a == 0) {
fork();
}
return 0;
}
How much fork()s are executed? the first one clearly occurs, will the second one occur? when I run the code with some printing (and checking fork succeeds) it changes from one run to another although by what I learned it should be always 2 forks. Is it some problem in my computer or program I'm using to run the code or am I missing something and this changing behavior can be explained?