Gapry
Gapry

Reputation: 373

How to implement a system call fork ()?

As we know, every process will call fork () in Linux. It will return 0 or 1 as normal or -1 to represent error. But, I don't know how to make a variable that can have two values at the same time. Can you give me some hits to help me to implement it?

Upvotes: 0

Views: 779

Answers (1)

David Schwartz
David Schwartz

Reputation: 182829

There isn't one variable that has two values. There are two variables, one in the parent and one in the child, and each has only a single value. The fork call returns twice. The process acts as if it was copied.

If you're interested in learning how fork is implemented, I'd suggest you start by looking at the actual implementation. Consider:

bool is_child()
{
    pid_t pid = getpid();
    // some system call that returns twice (like 'clone')
    return (getpid() == pid);
}

Here you have a function whose return value depends on which process it returns from. If you do j = is_child(); the variable j will be false in the parent and true in the child.

Here's a full working example:

    #include <sys/types.h>
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>

    bool my_fork()
    {
        pid_t pid = getpid();
        fork(); // we ignore the return value
        return pid == getpid();
    }

    int main(void)
    {
        bool j = my_fork();
        if (j)
            printf("parent\n");
        else
            printf("child\n");
        _exit (0);
    }

Upvotes: 1

Related Questions