Write a program that accepts an integer N as a command line input and then proce
ID: 3906132 • Letter: W
Question
Write a program that accepts an integer N as a command line input and then proceeds to launch N threads within that process. Each process should consist of an infinite loop that prints out “Thread k running” (once every second) where k is a process index (from 0 to N-1). After 5 seconds of running, your main program should kill process 0, then after another 5 seconds, should kill process 1, and so on until all processes have been terminated. At that time, your main program should itself terminate.solution to these problems should be written in C or C++ for Linux/windows.
Explanation / Answer
Dear Student,
Please find the code below :
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <signal.h>
using namespace std;
const int MAX_ARRAY_SIZE = 10; //array size
int pidArray[MAX_ARRAY_SIZE]; //array to hold process ids in order to kill them
int p = 0; //increment to add pid values
//'process is running' infinite loop function
void infiniteLoop(int n){
int t =0;
while(t - 6){
cout << " Process : " << n << " Running " << endl;
sleep(1);
t++;
}
}
// Creates a process with n number of child processes and adds each value into pidArray
void createProcess() {
pid_t pid = fork(); // creates a child process if 0, error if -1 , else is just parent process
if (pid == 0) {
cout << "I am child Process.." << endl;
infiniteLoop(int(getpid()));
exit(0);
}
else if (pid < 0){
cout << "Failed to fork!" << endl;
exit(-1);
}
else {
cout << "Parent Process : " << getpid() << endl;
pidArray[p] = int(getpid());
p++;
}
}
void killProcess(int n){
int cPid = n;
cout << "The parent pid of this process that is about to get killed is : " << cPid << endl;
kill(cPid,SIGTERM);
}
int main(int argc, char* argv[]) {
int n = strtol(argv[1], NULL, 10); //convert cmd line input to int
for (int i = 0; i < n; i++) { //create n # of processes
createProcess();
sleep(1); //create process every second
}
sleep(5);
//Iterate through the array of PIDs and kill after 5 seconds
for (int i = 0; i < MAX_ARRAY_SIZE;i++) {
int k = pidArray[i];
killProcess(k);
sleep(5);
}
return 0;
}
Happy Learning. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.