简体   繁体   中英

Unix fork() system call what runs 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 in a Unix OS (Ubuntu in my case). I can't for the life of me understand how this works. I know the fork() function splits my programs in two processes but from where? Does it create a new process and run the whole main function again, and if so why did the init() only run once and the printf() twice?

Why does the printf("pre fork()"); run twice and the init() function only once?

There's only one process until the fork. That is, that path is executed only once. After the fork there are 2 processes so the code following that system call is executed by both processes. What you ignore is that both terminate and both will call exit .

In your code you're not flushing stdio . So both processes do that (exit flushes stdio buffers) - that's why you're seeing that output.

Try this:

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

Or maybe

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM