Unix fork () system call works when?

void child(int pid){
    printf("Child PID:%d\n",pid);
    exit(0);    
}
void parent(int pid){
    printf("Parent PID:%d\n",pid);
    exit(0);
}

void init(){
    printf("Init\n");//runs before the fork
}


int main(){

    init();//only runs for parent i.e. runs once
    printf("pre fork()");// but this runs for both i.e. runs twice
    //why???

    int pid = fork();

    if(pid == 0){
        child(pid); //run child process
    }else{
        parent(pid);//run parent process
    }
    return 0;
}

output:

Init
pre fork()Parrent PID:4788
pre fork()Child PID:0

I have a process on a Unix OS (Ubuntu in my case). I can’t let my life understand how it works. I know that a function fork()separates my programs in two processes, but where from? Does he create a new process and run the entire main function again, and if so, why did he init()execute it only once and printf()twice?

Why is it executed printf("pre fork()");twice and the function init()only once?

+5
source share
1 answer

. , . 2 , , , . , , - , , exit.

stdio. , ( flush stdio buffers) - .

:

printf("pre fork()\n");
                  ^^ should flush stdout

, ,

printf("pre fork()\n");
fflush(stdout);
+22

All Articles