CITS2002 Systems Programming  
next CITS2002 CITS2002 schedule  

Creating a new process using fork()

fork() is very unusual because it returns different values in the (existing) parent process, and the (new) child process:

  • the value returned by fork() in the parent process will be the process-indentifier, of process-ID, of the child process;
  • the value returned by fork() in the child process will be 0, indicating that it is the child, because 0 is not a valid process-ID.

Each successful invocation of fork() returns a new monotonically increasing process-ID (the kernel 'wraps' the value back to the first unused positive value when it reaches 100,000).


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

void function(void)
{
    int  pid;                 // some systems define a pid_t

    switch (pid = fork()) {
    case -1 :
        printf("fork() failed\n");     // process creation failed
        exit(EXIT_FAILURE);
        break;

    case 0:                   // new child process
        printf("c:  value of pid=%i\n", pid);
        printf("c:  child's pid=%i\n", getpid());
        printf("c:  child's parent pid=%i\n", getppid());
        break;

    default:                  // original parent process
        sleep(1);
        printf("p:  value of pid=%i\n", pid);
        printf("p:  parent's pid=%i\n", getpid());
        printf("p:  parent's parent pid=%i\n", getppid());
        break;
    }
    fflush(stdout);
}

produces:

c: child's value of pid=0 c: child's pid=5642 c: child's parent pid=5641 p: parent's value of pid=5642 p: parent's pid=5641 p: parent's parent pid=3244

Of note, calling sleep(1) may help to separate the outputs, and we fflush() in each process to force its output to appear.

 


CITS2002 Systems Programming, Lecture 9, p1, 19th August 2024.