os161-1.99
 All Data Structures
pidcheck.c
00001 /*
00002  * pidcheck - simple test of fork and getpid
00003  *
00004  *  relies only on fork, console write, getpid and _exit
00005  *
00006  *  child prints its pid, parent prints childs pid and its own
00007  *
00008  */
00009 
00010 #include <unistd.h>
00011 #include <string.h>
00012 #include <stdlib.h>
00013 #include <stdio.h>
00014 #include <err.h>
00015 
00016 /* declare this volatile to discourage the compiler from
00017    optimizing away the parent's delay loop */
00018 volatile int tot;
00019 
00020 int
00021 main(int argc, char *argv[])
00022 {
00023   (void)argc;
00024   (void)argv;
00025   pid_t pid,pid2;
00026   int i;
00027   pid = fork();
00028   if (pid < 0) {
00029     warn("fork");
00030   }
00031   else if (pid == 0) {
00032     /* child */
00033     pid2 = getpid();
00034     /* print the child's PID, as seen by the child */
00035     printf("C: %d\n",pid2);
00036   }
00037   else {
00038     /* parent */
00039     /* try to delay long enough for the child to finish printing */
00040     tot = 0;
00041     for(i=0;i<1000000;i++) {
00042       tot++;
00043     }
00044     /* print the child's PID, as seen by the parent */
00045     printf("PC: %d\n",pid);
00046     /* print the parent's PID */
00047     pid2 = getpid();
00048     printf("PP: %d\n",pid2);
00049   }
00050   return(0);
00051 }
 All Data Structures