/* Copyright 2006 Paul... don't copy this for your hw... Author: Paul Picazo (http://pr.erau.edu/~picazdb3/) Course: CS420 (OS) Instructor : Matt Jaffe */ #include #include #include #include int main(int argc, char* argv[]) { //print a nice line break so our output is distinctly visible printf("\n"); //save (will go to children) original process id for later int thepid = getpid(); int fid; //we will store result of the fork() here int n = 0; //n + 1 will be the # of the child int numchildren; //numchildren is the number of child processes to start //usage: fork [int], with [int] being the number of child processes //if not given, defaults to 10 if(argc == 2) { numchildren = atoi(argv[1]); } else { numchildren = 10; } //print the parent info from the parent process before any forks printf("Parent Process (%d) starting.\n",thepid); //loop will only continue when it is the parent process while((thepid == getpid()) && n < numchildren) { fid = fork(); //do the actual fork if(fid == 0) //this branch taken only by the children { int cpid = getpid(); //store the child id int ppid = getppid(); //store the parent id //In order to visualize the processes running concurrently, //we will artificially delay each process between 1-10 secs //Random seed needs to have more than the tick because //the ticks have a high chance of not being unique srand48( (unsigned)time( NULL ) * cpid ); int waittime = (int) 10 * (lrand48() / (2147483649.0)); sleep(waittime); //print the childs info from the child process printf("\tFrom Child Process #%d (%d) Parent (%d) : %d secs\n", n + 1, cpid, ppid, waittime); } else if(fid < 0) //fork was not successful { printf("ERROR: could not fork on fork #%d\n", n+1); } else //this branch taken only by the parent { //print the parent info from the parent after forks printf("Parent Process (%d) spawning child #%d (%d)\n", thepid, n+1, fid); n++; } } if(fid != 0) //if not a child { int status; //wait until all children have terminated while (wait(&status) != -1) {} printf("Parent Process (%d)", thepid); printf(" is done waiting for children and will now terminate!\n\n"); } return 0; }