Forking Example
2001-11-23 02:37:41
Category: c:runtime
Description: Example of basic forking in c
Author: detour
Viewed: 4573
Rating: (19 votes)


/* fork.c written by detour@metalshell.com
 *
 * simple forking example
 * 
 * fork() requires unistd.h
 *
 * http://www.metalshell.com/
 *
 */
 
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
 
int main(int argc, char *argv[]) {
  pid_t pid;
 
  pid = fork();
 
  if (pid == 0) {
    printf("\nThis is the child process talking.\n");
    printf("Use 'ps -ax | grep %s' to verify child process.\n", argv[0]);
    printf("Sleeping for 20 seconds.\n");
    /* Flush our output before we sleep */
    fflush(stdout);
    sleep(20);
    printf("\nChild exiting\n");
  } else if (pid != -1) {
    /* This is the parent process, so lets exit. */
    printf("Parent exiting.\n");
    exit(0);
  } else {
    printf("There was an error with forking");
    exit(1);
  }
 
}