1 /*
2 Copyright 2006 Paul... don't copy this for your hw...
3 Author: Paul Picazo (http://pr.erau.edu/~picazdb3/)
4 Course: CS420 (OS)
5 Instructor : Matt Jaffe
6 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/types.h>
10 #include <time.h>
11
12 int main(int argc, char* argv[])
13 {
14 //print a nice line break so our output is distinctly visible
15 printf("\n");
16
17 //save (will go to children) original process id for later
18 int thepid = getpid();
19 int fid; //we will store result of the fork() here
20
21 int n = 0; //n + 1 will be the # of the child
22 int numchildren; //numchildren is the number of child processes to start
23
24 //usage: fork [int], with [int] being the number of child processes
25 //if not given, defaults to 10
26 if(argc == 2)
27 {
28 numchildren = atoi(argv[1]);
29 }
30 else
31 {
32 numchildren = 10;
33 }
34 //print the parent info from the parent process before any forks
35 printf("Parent Process (%d) starting.\n",thepid);
36
37
38 //loop will only continue when it is the parent process
39 while((thepid == getpid()) && n < numchildren)
40 {
41 fid = fork(); //do the actual fork
42 if(fid == 0) //this branch taken only by the children
43 {
44 int cpid = getpid(); //store the child id
45 int ppid = getppid(); //store the parent id
46
47 //In order to visualize the processes running concurrently,
48 //we will artificially delay each process between 1-10 secs
49
50 //Random seed needs to have more than the tick because
51 //the ticks have a high chance of not being unique
52 srand48( (unsigned)time( NULL ) * cpid );
53 int waittime = (int) 10 * (lrand48() / (2147483649.0));
54 sleep(waittime);
55
56 //print the childs info from the child process
57 printf("\tFrom Child Process #%d (%d) Parent (%d) : %d secs\n",
58 n + 1, cpid, ppid, waittime);
59 }
60 else if(fid < 0) //fork was not successful
61 {
62 printf("ERROR: could not fork on fork #%d\n", n+1);
63 }
64 else //this branch taken only by the parent
65 {
66 //print the parent info from the parent after forks
67 printf("Parent Process (%d) spawning child #%d (%d)\n",
68 thepid, n+1, fid);
69 n++;
70 }
71 }
72 if(fid != 0) //if not a child
73 {
74 int status;
75 //wait until all children have terminated
76 while (wait(&status) != -1)
77 {}
78 printf("Parent Process (%d)", thepid);
79 printf(" is done waiting for children and will now terminate!\n\n");
80 }
81 return 0;
82 }