In: Computer Science
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char **argv) { int count; if ((argc != 2) || (sscanf(argv[1],"%d",&count) != 1)) { fprintf(stderr,"Usage: %s <integer>\n", argv[0]); exit(1); } pid_t pid1, pid2; while (count > 0) { pid1 = fork(); if (pid1 > 0) { pid2 = fork(); count = count - 2; } else if (pid1 == 0) { count = count - 1; } } exit(0); }
Question #1 [2 pts]
If the command-line argument passed to this program is 0, this program creates no process. How many processes does this program create if the command-line argument is 1?
Question #2 [3 pts]
How many processes does this program create if the command-line argument is 2?
Question #3 [12 pts]
Let T(n) be the number of processes this program creates when its input is n (the answer to Question #1 above is thus T(1)).
Write an recursive formula (i.e., a recurrence relation) that gives T(i) as a function of one or more values of T for smaller input (i.e., smaller i). Explain your reasoning.
Feel free to double-check your formula by actually running the program and possibly augmenting it so that it allows you to count processes in whichever way you want.
Question #4 [3 pts]
Say the maximum number of processes that can be created on your machine is 100,000 (you can find out the actual number of your machine with ulimit -u).
What is the smallest value of the command-line argument for which the above program would experience failed fork() calls?
Solution :
ANSWER 1:
The number of processes created using fork system call is given by the following formula -
so, if the value of ommand-line argument is 1, the number of processes created will be equal to .
ANSWER 2:
If the value of ommand-line argument is 2, the number of processes created will be equal to .
ANSWER 3:-
So, it T(n) is a function of one or more value of T, the following recurrence formula will be formed
where n is the number of process.
The following is the more simpler code-
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char **argv) {
int count;
if((argc!=2) || (sscanf(argv[1],"%d",&count) !=1) ){
fprintf(stderr,"Usage:%s<integer>\n",argv[0]);
exit(1);
}
int pid_t,pid1,pid2;
while(count>0){
pid1 = fork();
printf("\n Hello I am the process.My pid is %d \n",getpid());
fprintf( stderr, "1. parent process ID: %d\n", getppid() );
if(pid1>0){
pid2 = fork();
printf("\n Hello I am the process.My pid is %d\n ",getpid());
fprintf( stderr, "1. parent process ID: %d\n", getppid() );
count = count-2;
}
else if(pid1==0){
printf("\n Hello I am the process.My pid is %d \n",getpid());
fprintf( stderr, "1. parent process ID: %d\n", getppid() );
count = count-1;
}
}
exit(0);
return 0;
ANSWER 4:
Given that the maximum number of processes that can be created on your machine is 100,000.
This means
So, 17 is the smallest value of command line argument for which the above program would experience failed fork() calls.