In a C or C++ program, fork() can be used to create a new process, known as a child process. This child is initially a copy of the the parent, but can be used to run a different branch of the program or even execute a completely different program. After forking, child and parent processes run in parallel. Any variables local to the parent process will have been copied for the child process, so updating a variable in one process will not affect the other.

Consider the following example program:

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

int main(int argc, char **argv)
{
    printf("--beginning of program\n");

    int counter = 0;
    pid_t pid = fork();

    if (pid == 0)
    {
        // child process
        int i = 0;
        for (; i < 5; ++i)
        {
            printf("child process: counter=%d\n", ++counter);
        }
    }
    else if (pid > 0)
    {
        // parent process
        int j = 0;
        for (; j < 5; ++j)
        {
            printf("parent process: counter=%d\n", ++counter);
        }
    }
    else
    {
        // fork failed
        printf("fork() failed!\n");
        return 1;
    }

    printf("--end of program--\n");

    return 0;
}

This program declares a counter variable, set to zero, before fork()ing. After the fork call, we have two processes running in parallel, both incrementing their own version of counter. Each process will run to completion and exit. Because the processes run in parallel, we have no way of knowing which will finish first. Running this program will print something similar to what is shown below, though results may vary from one run to the next.

--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
--end of program--
child process: counter=4
child process: counter=5
--end of program--

  1. maperezxochicale says:

    Thank you, that is a very clean example. I have read that fork can be used to run two process as is stated in the following example [1]; however, I have not managed to I am wondering whether you if it is possible to run the below process in parallel. I will appreciate your time in any suggestion or guidance that you can provide. ~MA

    #include
    #include
    main()
    {
    system(“term -e ./task1”);
    system(“term -e ./task2”);
    return 0
    }

  2. smorgasbordator says:

    Would you happen to know how quick it takes the program to copy the data from the parent to the child?

  3. shagufta shaheen says:

    a total of many processes would be created in the function fork test() given below, excluding the main process that called fork test()? how many times will “Whatsup” be printed. Briefly explain your answer.
    void fork_test()
    {
    if (fork() !=0)
    {
    if (fork () !=0)
    fork();
    else
    printf(“hello 1\n”);
    }
    else
    {
    if(fork() !=0)
    {
    printf(“hello\n”;
    }
    else
    {
    fork();
    }
    }
    printf(“Whatsup\n”);
    }

  4. shagufta shaheen says:

    ans plz

  5. waseem says:

    a total of many processes would be created in the function fork test() given below, excluding the main process that called fork test()? how many times will “Whatsup” be printed. Briefly explain your answer.
    void fork_test()
    {
    if (fork() !=0)
    {
    if (fork () !=0)
    fork();
    else
    printf(“hello 1\n”);
    }
    else
    {
    if(fork() !=0)
    {
    printf(“hello\n”;
    }
    else
    {
    fork();
    }
    }
    printf(“Whatsup\n”);
    }

  6. SANJAYA KUMAR PADHY says:

    I want to exercise some UNIX commands using C language. When I include header file and when I use fork() method it gives me a compile time error: “can not include unistd.h”. I check on he Internet and the fork() method is available in header file only. Please help me on this. please let me know how to inlcude the above header file. i m using C compiler for in windows 7 64 bit OS.

  7. share12 says:

    Thank you for your example. When I try to run it, and as you said trace may be different, but after 2 or 3 run, I still get the same trace: Can you explain it?
    –beginning of program
    parent process: counter=1
    parent process: counter=2
    parent process: counter=3
    parent process: counter=4
    parent process: counter=5
    –end of program–
    child process: counter=1
    child process: counter=2
    child process: counter=3
    child process: counter=4
    child process: counter=5
    –end of program–

  8. bahar says:

    Hi,I want to write a quick sort in c using a fork so that any part of the code is done every 3 core of my laptop,
    I need help
    please

  9. r2d2 says:

    Hello! Thanks for this example. I am getting the same output as share12.

    –beginning of program
    parent process: counter=1
    parent process: counter=2
    parent process: counter=3
    parent process: counter=4
    parent process: counter=5
    –end of program–
    child process: counter=1
    child process: counter=2
    child process: counter=3
    child process: counter=4
    child process: counter=5
    –end of program–

    I’m wondering why it seems that the parent process completes and ends before the child begins its work.

  10. bb8 says:

    Suppose we have this code:

    int i;
    for (i=0; i<3; i++)
    fork();
    printf("Hello");

    1. How many times "Hello" is printed on the screen?
    2. Draw the tree of processes: parent and child

  11. roro says:

    Write a simple C language program to:
    ? Start a process using fork command
    ? Get Status info of the running process
    ? Terminate the process
    ? Compile and execute the C program.

  12. roro says:

    please hlep me

  13. soniya says:

    @r2d2 and share12 .. run the for loop for more than 50 times and see

  14. mark says:

    thanks a lot, we are currently learning about it, and i dont really get is. I’ll check it home.

  15. Alif says:

    Is forking copy everything inside the program, including threads inside the program??

  16. Saiher says:

    Assalam o Alaikum. Plz help me how we can write this program???
    You are required to write a simple C language program to:

    1. Create a process using fork call
    2. Get and print status information of the running processes
    3. Use pipe call for inter-process communication between processes
    4. Terminate process
    5. Compile & run C program on Linux Operating system.

    In the main() function, first of all you will establish a channel for processes to communicate through pipe system call. After successful creation of pipe, you will create child process through fork() system call.

    In the child process, you will have to display your own student Id through the pipe or channel established between processes. In the parent process, you will have to display your own student name through the pipe or channel established between processes.

    You will also print the status information of Parent and Child process by using user-defined function printInfo(). The status information includes Process Id and Parent Id in case of Child process and Process ID and Child Id in case of Parent process.

    Compilation & Execution of Program:

    You will compile your file with your student ID. For example, if your student ID is BC123456789