DEV Community

Naman Tamrakar
Naman Tamrakar

Posted on • Edited on

How to create new process of current program in c using fork

In this post I will explain how one can clone or create new process of current c program using fork.

Why it is named fork?

When we create child processes and these child processes can also create their own child process It form a tree like structure, So May be that is the reason it is named as fork.

So lets write a simple program to create a clone of current process.

#include <stdio.h>
#include <unistd.h> // fork

int main() {
    fork();
    printf("Hello world -> My PID is %d\n", getpid());
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Hello world -> My PID is 18131
Hello world -> My PID is 18132
Enter fullscreen mode Exit fullscreen mode

So let me explain what is happening above.

The execution of program start from the main function and it first get fork() which create a new clone of current process and now both child parent process continues from here and get statement printf so print it on console.

Note: Whenever program get a fork() statement then at the same instant a clone of it is create and start executing from there only in both the process i.e. Parent and Child.


Let's explore more about fork by taking this example.

#include <stdio.h>
#include <unistd.h> // fork

int main() {
    printf("Program execution start here.\n");
    int r = fork();
    printf(
        "Hello world -> My PID is %d, I am %s process\n", 
        getpid(), 
        r==0 ? "child" : "parent"
    );
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Program execution start here.
Hello world -> My PID is 548, I am parent process
Hello world -> My PID is 549, I am child process
Enter fullscreen mode Exit fullscreen mode

Let me explain what is happening above.

Program execution start and get first line printf so print it on console then get fork statement so create new child process at this line. Now in parent program fork return pid of child process but in child process it returns 0 so we check for return value and print based on that only.

NOTE: fork() returns -1 if it failed to clone the process.


Here is one more example

#include <stdio.h>
#include <unistd.h> // fork

int main() {
    printf("Program execution start here.\n");

    int r;
    for (int i=0; i<5; i++) {
        if ((r=fork())==0) {
            break;
        }
    }
    printf(
        "Hello world -> My PID is %d, I am %s process\n", 
        getpid(), 
        r==0 ? "child" : "parent"
    );
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Program execution start here.
Hello world -> My PID is 635, I am child process
Hello world -> My PID is 636, I am child process
Hello world -> My PID is 637, I am child process
Hello world -> My PID is 638, I am child process
Hello world -> My PID is 634, I am parent process
Hello world -> My PID is 639, I am child process
Enter fullscreen mode Exit fullscreen mode

The output of this program seems weird as parent program output before the last child process. Let me explain what happening in the above code.

In the loop we execute fork() and response is stored in predefined variable r. So in the child process It will be zero so loop breaks out in child process and further program executes. But in parent program loop will not break and it will continue to create new child process.

So these child process are being created and executed in parallel by CPU. But the last child process execute after the child process because after creation of last child process loop breaks and continues to execute printf statement in parent process.

But why last process executed after parent?

One reason may be it take some time to make clone of child process in memory and schedule it by CPU to execute. But the parent program that is already running so it execute first.

NOTE: The above reason for execution order may be not accurate. It is just one assumption made by me. So the execution order may vary from machine to machine.

So that's it about fork to clone current process. In the above I may be wrong somewhere. Please write in comment If you find so. Thank you so much for reading it completely.

Summary

  • fork can be used to clone current process.
  • The execution of child process start from where we get fork() statement. So child process execute from there only.
  • fork returns PID of child process created in parent program but returns 0 in child process created. So one can use their logic based on return value to differentiate between child and parent process.

Please give it a thumbs up If you like this post.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

You don't handle when fork() fails and returns -1.

Collapse
 
namantam1 profile image
Naman Tamrakar

Thanks for reminding. I will add it too.