Forking the Grandchildren

I wrote about forking a while back, in June 2015. The fork splits a program into two processes, each capable of handling different tasks simultaneously. The power behind this trick is the fork() function.

Before you get all excited, be aware that the fork() function isn’t available in Windows. It shouldn’t be available in the Unix environment either, but it is and so everyone deals with it.

The typical fork() example has a program split into two parts: The fork duplicates the program and the code uses the program’s process ID (PID) to determine which version is the original, or parent, and which is the duplicate, or child. The getpid() function returns the process ID, which is how the code knows which version of itself is running.

It’s possible to fork a program more than once, though things get hairy quickly. The code must track all of its various clones lest the program continue to spawn children like over-fed Tribbles.

The following code forks a program into a parent and child process. In the code, when the child process is identified, it forks into a grandchild process.

2022_05_21-Lesson.c

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

int main()
{
    pid_t parent,a,b;

    parent = getpid();
    fork();
    a = getpid();
    if( a==parent )
    {
        printf("I am the parent: %d\n",parent);
    }
    else
    {
        fork();
        b = getpid();
        if( a==b )
            printf("I am the child: %d\n",a);
        else
            printf("I am the grandchild: %d\n",b);
    }

    return(0);
}

The parent process ID is obtained at Line 8, before the fork() call.

After the fork() call, at Line 10, variable a holds the current process’ ID. If it’s the parent (Line 11), the process ID is output. Otherwise the else block is executed.

In the else block, a second fork is issued at Line 17. This operation takes place only in the child process. Variable b is assigned the current process ID, then an if-else block outputs text based on whether the child or grandchild is running.

Whew!

This code can be complex, not because of the simple decision tree but because it runs three programs (or processes) not just one. Here’s sample output:

I am the parent: 24630
I am the child: 24631
I am the grandchild: 24632

Forking isn’t the best way to run two separate processes, as I wrote earlier. A better approach for a program to do two (or more) things at once is to create a new thread. A thread is like a process, but more focused. I cover creating threads in next week’s Lesson.

Leave a Reply