Write a program using C to generate a binary tree of processes. The input to the
ID: 3672635 • Letter: W
Question
Write a program using C to generate a binary tree of processes. The input to the program includes the number of levels in the tree. The maximum number of levels is 5, but the program should work for a general case of any number. Use command line arguments.
Example of a program run is as follows:
ecs416lin213.cecs.csuld.edu:1>p1 4
Please show output listing using N = 3. Draw a tree diagram showing the process IDs in circles.
Starting point:
/**************************************************************************/
/* PROGRAM: lab2.c */
/* DESCRIPTION: This program generates a chain of processes */
/* using fork(). The number of processes n is a command line argument. */ /* Each process sleeps for a random time less than 10 seconds then prints out */
/* process ID, parent ID, and child ID */
/**************************************************************************/
# include <stdio.h>
# include <stdlib.h>
# include <sys/types.h>
# include <unistd.h>
int main(int argc, char *argv[])
{
int i, m, n, sleeptime, seed;
pid_t childpid;
if (argc !=2) {
printf(" Usage: %s processes ", argv[0]);
exit(1);
}
n = atoi(argv[1]); m = 10;
childpid = 0;
for (i=0; i<n;i++)
if (childpid = fork()) break;
if (childpid == -1) {
perror (" The fork failed ");
exit(1);
}
printf(" %d: process ID:%6ld parent ID:%6ld child
ID:%6ld",i, (long)getpid(), (long)getppid(), (long)childpid);
seed = (int)(getpid() + childpid);
8
srand(seed);
/* since each process has a different childpid, using the childpid
as the seed number will restart the random function.
Therefore, each process will have a different sleeptime
*/
sleeptime = rand()%m;
printf (" sleep = %d ", sleeptime);
sleep(sleeptime);
exit(0);
}
Explanation / Answer
This program will work for any number of process by just passing the command line argument without modification of the program.
but just pass the only one value after the program name i.e n value..
Exmaple See the : p 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.