How many processes does the following piece of code create? Why? int main() {for
ID: 3819636 • Letter: H
Question
How many processes does the following piece of code create? Why? int main() {fork (); fork (); fork (); return 0;} a) Write a C/C + + - program that creates a chain of 10 processes and prints out their process ids and relationships. For example, process 1 is the parent of process 2, process 2 is the parent of process 3, process 3 is the parent of 4 and so on. Each child has to print out all her ancestors identified by the process ids. b) Write a C/C + + - program that creates a fan of 10 processes. That is, process 1 is the parent of prcocesses 2, 3, 4, 5, 6, and so on.Explanation / Answer
1. The given code will create 4 processes. It will create 1 process as parent process which is the program it self and using 3 fork() calls It will create 3 more child processes. So total processes it will create will be 4.
2. a)
Here is the code, I have included explanation as comments
#include<stdio.h>
#include<unistd.h>
int main(){
for( int generation = 0 ; generation < 10 ; ++generation )
{
int pid = fork();// here we are forking the new process
if( pid != 0 )
{
break; // breaking the loop when parent process encountered
}else{
// printing child process id and parent process id of child process
printf("child %d of parent %d ", getpid(),getppid());
}
}
return 0;
}
2. b)
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main( void )
{
printf( "I am parent pid %d ", getpid());// Here we are printing parent process id
for ( int i = 0; i < 10; i++ )
if ( fork() == 0 )// here we are creating child process id and checking condition for child process execution
{
printf( "I am child pid %d from pid %d ", getpid(), getppid());
exit( 0 );
}
for ( int i = 0; i < 10; i++ )// here we are waiting for complete execution of each child process
wait( NULL );
}
If you have any queries or doubts regarding this solution then please do comment.
Good luck.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.