Search code examples
cunixpid

Creating one grandparent, parent, and child process using fork()


I am trying to fork processes to create exactly one grandparent, parent, and child respectively and display each pid to the standard output. How can I accomplish this? Here is my current code and output:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
int pid, status, status2;
pid = fork();
switch (pid)
{
    case -1: // An error has occured during the fork process.
        printf("Fork error.");
        break;
    case 0:
        pid = fork();
        switch (pid)
        {
            case -1:
                printf("Fork error.");
                break;
            case 0:
                printf("I am the child process C and my pid is %d\n", getpid());
                break;
            default:
                wait(&status);
                printf("I am the parent process P and my pid is %d\n", getpid());
                break;
        }
    default:
        wait(&status2);
        printf("I am the Grandparent process G and my pid is %d\n", getpid());
        break;
    }
}

And my output:

I am the child process C and my pid is 8208
I am the Grandparent process G and my pid is 8208
I am the parent process P and my pid is 8207
I am the Grandparent process G and my pid is 8207
I am the Grandparent process G and my pid is 8206

Solution

  • fork() doesn't return 1 in the parent, it returns the pid of the child.

    You probably want to change your case 1s to default.

    Also, in your outer switch, the case 0 falls through into case 1. You probably want a break; following the inner switch, between lines 28 and 29.