In: Computer Science
Write a C or C++ program using the fork() system call function. You will need to create 3 processes – each process will perform a simple task.
Firstly, create an integer "counter" initialized to a random value between 1 and 100. Print this number to the console. This can be done by:
Including the stdio.h and stdlib.h libraries
Using the rand() function to generate your randomly generated number
The main thread consists of the parent process. Your job is to create 3 child processes, as follow:
Process 1 prints out its current process ID and its parent process ID
The parent process will wait until this child is completed using the wait() function
Process 2 will create a for loop that increments the "counter" variable by 1, ten times. Print out the counter for each iteration.
The parent process will not wait for this child process to end, but instead it will print out the counter value to show that the child process does not share memory with the parent process.
Note: There’s a chance the code will execute out of order because the parentprocess does not wait for the child process.
Process 3 will create a for loop that increments the "counter" variable by 1, ten times. Print out the counter for each iteration.
The parent process will not wait for this child process and instead, the parent process will kill the child with the kill command.
Note: This is to show that this will either not run at all or only partially run due to being killed manually.
To run this CPP program on Unix or Linux, type: g++ prog1.cpp
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
//counter init
int counter =rand()%100+1;
printf("Counter:%d\n",counter);
//creates process 1
int pid1=fork();
if(pid1==0)//child
{
printf("Process ID:%d\nParnetID:%d\n",getpid(),getppid());
}
else{
wait(NULL);
//create proccess 2
int pid2=fork();
if(pid2==0)
{
for(int i=0;i<10;++i)
{
printf("Process 2: Counter:%d\n",counter);
counter++;
}
}
else{
//print counter
printf("Parent Process: Counter:%d\n",counter);
//create process 3
int pid3=fork();
if(pid3==0)
{
for(int i=0;i<10;++i)
{
printf("Process 3: Counter:%d\n",counter);
counter++;
}
}
else{
kill(pid3,SIGKILL);}
}
}
}
COMMENT DOWN FOR ANY QUERIES AND ,
LEAVE A THUMBS UP IF THIS ANSWER HELPS YOU.