Monday, June 10, 2013

A Demonstration of the UNIX fork() Call

UNIX's fork() call is a fantastic way to have one executable divide itself into two processes, each of which can perform different code from a single codebase. It is also useful for apps that should be started from a command line but shouldn't be vulnerable to being killed with Control-C or the death of the shell. This is how daemons work in UNIX/Linux/OS X. I believe (though I may be mistaken) that this is the basis of Google Chrome's multi-process browsing feature.

 //  
 // fork.c  
 //  
 // Created by SevenBits on 4/14/13.  
 //  
 // This demonstrates how to fork a process. Basically, what happens is, one  
 // process will fork itself, creating a cloned process. The return value of  
 // the fork() call can be used to direct one process to perform one task,  
 // and the clone to perform another! Inter-process communication is also  
 // possible.  
 #include <stdio.h>  
 #include <unistd.h>  
 #include <stdlib.h>  
 int main() {  
   printf("We're going to fork ourselves. This will spawn multiple processes,");  
   printf(" which will each count from 1 to 100 in a different process.\n");  
   pid_t pid = fork();  
   int i;  
   switch (pid) {  
     case -1:  
       printf("ERROR! Something went wrong!\n");  
       return 1;  
       break;  
     case 0:  
              for (i = 0; i < 100; i++) { // This runs in one process.  
                printf ("A: %d\n", i);  
         sleep(1);  
              }  
       break;  
     default: // This runs in another process (the parent).  
              for (i = 0; i < 100; i++) {  
                printf ("B: %d\n", i);  
         sleep(2);  
              }  
       break;  
   }  
   return 0;  
 }  

I officially place this code in the public domain. Do whatever.

No comments: