The UNIX Operating System

TOP

UP


Ray Seyfarth

ORCA


Computer Science

COST

USM




Concurrency using fork in UNIX


    #include <iostream.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    
    int main ( int argc, char **argv )
    {
        int i, pid;
    
        pid = fork();
    
        cout << pid << endl;
    
        for ( i = 0; i < 5; i++) {
            cout << getpid() << ' ' << i << endl;
        }
    
        if ( pid ) wait(NULL);
    }
    

  • New process starts execution by returning from fork

  • Child and parent are nearly identical
    parent gets the child process id from fork
    child gets 0 back from fork

  • Parent should wait for child to exit


University of Southern Mississippi
Ray.Seyfarth@usm.edu
Updated 20:05 Jun 5, 2000