Question: Need help with my program #include #include #include #include #include / / Function to compute factorial int factorial ( int n ) { if (

Need help with my program
#include
#include
#include
#include
#include
// Function to compute factorial
int factorial(int n){
if (n ==0|| n ==1)
return 1;
else
return n * factorial(n -1);
}
// Function to check if a number is prime
int isPrime(int num){
if (num =1)
return 0;
for (int i =2; i * i = num; i++){
if (num % i ==0)
return 0;
}
return 1;
}
int main(){
pid_t child_pid;
int n;
// Prompt user for the number of child processes to create
printf("Enter the number of child processes to create (less than 5): ");
scanf("%d", &n);
// Validate input
if (n 1|| n >4){
printf("Invalid input. Please enter a number between 1 and 4.
");
return 1;
}
// Display initial message
printf("Parent process (PID: %d) is creating %d child processes.
", getpid(), n);
// Create child processes
for (int i =0; i n; i++){
child_pid = fork();
if (child_pid 0){
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (child_pid ==0){
// This code will be executed by the child process
// Print child's identifier (PID) and the task it is performing
printf("Child %d (PID: %d) is performing a custom task.
", i +1, getpid());
// Perform different tasks based on child number
switch (i){
case 0:
printf("Child %d (PID: %d) is computing the factorial of 5.
", i +1, getpid());
printf("Child %d (PID: %d) completed its task. Result: %d
", i +1, getpid(), factorial(5));
break;
case 1:
printf("Child %d (PID: %d) is finding prime numbers up to 20.
", i +1, getpid());
printf("Child %d (PID: %d) completed its task. Result: ", i +1, getpid());
for (int j =2; j =20; j++){
if (isPrime(j))
printf("%d ", j);
}
printf("
");
break;
case 2:
printf("Child %d (PID: %d) is performing a custom task.
", i +1, getpid());
printf("Child %d (PID: %d) completed its task. Result: Custom task completed.
", i +1, getpid());
break;
// Add more cases for additional child processes if needed
}
exit(EXIT_SUCCESS);
}
}
// This code will be executed by the parent process
// Wait for all child processes to finish
for (int i =0; i n; i++){
wait(NULL);
}
printf("All child processes have completed. Parent (PID: %d) is displaying the final message.
", getpid());
return 0;
}
 Need help with my program #include #include #include #include #include //

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!