fork

Gamma: Version 4.0
Prev |  | Next

# `fork`

`fork` -- duplicates a process.

## Syntax

    fork ()

## Arguments

none

## Returns

A positive task id that identifies the child process, and 0 that identifies the parent process to the child; or -1 if an error occurred. The errno is set if an error occurs.

## Description

The `fork` function creates a new process identical to the calling (parent) process except for a unique process ID. The child process has a different parent process ID and its own copy of the parent file descriptors. The child process does not inherit outstanding signals.

## Example

The following example illustrates using the `fork` function with `if` syntax. This is a useful way of separating the two, identical processes produced from `fork`. The first block of code applies to the parent process, while the second block applies to the child.

        #!/usr/cogent/bin/gamma

        if ((childID = fork()) > 0)
        {
          princ("P> My ID is: ", getpid(),"\n");
          princ("P> My child's ID is: ", childID, "\n");
          signal(SIGCHLD, #princ("P> Signal received that my child -- ",
                                 childID, " -- has died.\n"));
          princ("P> Waiting for my child.\n");
          w = wait(childID);
          princ("P> wait() returned this: ", w, "\n");
        }
        else
        {
          sleep(2);
          if (childID == -1)
            error("C> An error occurred.\n");
          else
            {
              princ("C> I am the child process.\nC> My process ID is: ",
                    getpid(), "\n");
              sleep(2);
              princ("C> Time to exit.\n");
              exit_program(3);
            }
        }

Will produce these results:

        P> My ID is: 1225
        P> My child's ID is: 1226
        P> Waiting for my child.

(after 2 seconds)

        C> I am the child process.
        C> My process ID is: 1226

(after 2 more seconds)

        C> Time to exit.
        P> Signal received that my child -- 1226 -- has died.
        P> wait() returned this: (1226 3 nil nil)

See the Starting Programs section of the Common Functions chapter (Tutorial One), or the Start a Process section of the Common Functions for Any Program chapter (Tutorial Two) in the Cogent Tools Demo and Tutorials book for examples of this function used in context.

## See Also

`exec`, `wait`

Prev | Home | Next
`exit_program` | Up | `getenv`

Copyright 1995-2002 by Cogent Real-Time Systems, Inc.