Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

0.1: Write a C program in the Linux/UNlX/MacOS environment? - The program should

ID: 668446 • Letter: 0

Question

0.1: Write a C program in the Linux/UNlX/MacOS environment? - The program should create a shared memory region which contains an array of 100 integers (where each variable has the value in range 1000 - 4000) - The program should create two child processes - The parent process will fill the array with a set of random integers ( Please use rand() function to generate random numbers) - The Child Process - 1 will find the minimum of the numbers and store it in the minimum variable. - The Child Process - 2 will find the average of the numbers from the array and store it in the maximum variable. - The parent process will wait for the child processes to complete and then print the minimum, maximum and the range (maximum - minimum) on the screen.

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>

int main ()
{
int w, h, i, j;

/* Read the width and height */
scanf ("%d %d", &w, &h);

/* Create and read the entire array */
int *arr = malloc (w * h * sizeof (int));
for (i = 0; i < w * h; ++i)
scanf ("%d", &arr[i]);
arr[i]=100;

/* Obtain a shared memory segment with the key 42 */
int shm = shmget (42, h * sizeof (int), IPC_CREAT | 0666);
if (shm < 0)
{
perror ("shmget");
return 1;
}

/* Attach the segment as an int array */
int *row = shmat (shm, NULL, 0);
if (row < (int *) NULL)
{
perror ("shmat");
return 1;
}

for (i = 0; i < h; ++i)
/* Create h children and make them work */
if (!fork ())
{
for (j = row[i] = 0; j < w; ++j)
row[i] += arr[i * w + j];
return 0;
}

int pid;
int status;
printf("Hello World! ");
pid = fork( );
if(pid == -1) /* check for error in fork */
{
perror("bad fork");
exit(1);
}
if (pid == 0)
printf("I am the child process. ");
else
{
wait(&status); /* parent waits for child to finish */
printf("I am the parent process. ");

/* Wait for the children to finish up */
for (i = 0; i < h; ++i)
wait (&j);

/* Sum the row totals */
for (i = j = 0; i < h; ++i)
j += row[i];

printf ("%d ", j);

/* Detach the shared memory segment and delete its key for later reuse */
shmdt (row);
shmctl (shm, IPC_RMID, NULL);

free (arr);
return 0;
}