Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix fork() system call what runs when?

Tags:

c

linux

fork

unix

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?

like image 252
boogie666 Avatar asked Jan 14 '12 16:01

boogie666


People also ask

Which process executes first after a fork () system call is made?

It is simply that the parent will fork() then wait() for the child to complete.

What is the use of fork () command in Unix?

What is a Fork()? In the computing field, fork() is the primary method of process creation on Unix-like operating systems. This function creates a new copy called the child out of the original process, that is called the parent. When the parent process closes or crashes for some reason, it also kills the child process.

What does fork () do in Linux?

fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. The child process and the parent process run in separate memory spaces.

What type of values does the Unix system call fork return?

RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.


1 Answers

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);
like image 58
cnicutar Avatar answered Oct 24 '22 15:10

cnicutar