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

I am new to C and the concept of shared memory, I am trying to compute the max a

ID: 3650688 • Letter: I

Question

I am new to C and the concept of shared memory, I am trying to compute the max and min of array of integers by creating a shared memory in the parent and the 2 child must attach to it ,
I am confused about the way to write the elements of the array to shared memory,
The output always gives me the first element for both the max and min which is wrong

could you tell me where exactly I am going wrong ? which lines in the code exactly I need to change?

Thanks

here is what I have so far:

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

void main() {

pid_t pid;
key_t key = 4567;
int shm_id = shmget(key, 100, ((sizeof(int))*12) | 0666);
int a[] ={23, 54,101,32,54,26,90,78,23,10};
int i;
int max = a[0];
int min = a[0];
pid = fork();
if (pid==0) {
int* shared_memory = shmat(shm_id, NULL, 0);
for (i=0; i<10; i++)
{
if (a[i] < min )
min = a[i];
}
a[10] = min; // store min in the 11th index
}
else{
pid = fork();
if (pid ==0){
int* shared_memory = shmat(shm_id, NULL, 0);
for (i=0; i<10; i++)
{
if (a[i] > max )
max = a[i];
}
a[11] = max; // store max in the 11th index
}
else {
wait(NULL);
wait(NULL);
printf ("the max is %d", max);
printf("the min is %d", min);
}
}
}

Explanation / Answer

void *shmat (int shmid, const void *shmaddr, int shmflg); When you attach shared memory (with the shmat call), it returns the address of shared memory (provided that shmaddr is otherwise NULL). Then you use that address as your array. Once you have the address, you use it as if it were just a regular local array or buffer. For ease of use, I suggest to cast as a char * array. Fewer headaches that way. Added: I can try. You did not number your lines. int a[] = {23, 54,101,32,54,26,90,78,23,10}; «--- This is your line. A local array of some numbers. int* shared_memory = shmat (shm_id, NULL, 0); «--- This is your line. You set the pointer to shared space. Now you need to put the numbers in the list into the shared space. Of course you could just get the min and max right of of the local array, a, but that does not meet the assignment. You have to use shared memory as the point of the exercise. So let us copy the numbers into the new shared list area. for (i = 0; i < 10; shared_memory[i] = a[i]; i++); Okay, now lets scan them for the min and the the max value. We know they are integers. int n_min = INT_MAX; /* Got to be less than this. */ int n_max = -INT_MAX; /* Got to be more than this. */ if (!fork ()) { /* Spawned a subprocess. This one for finding min. */ ? for (i = 0; i < 10; i++) { ? ? if (shared_memory[i] n_max) n_max = shared_memory[i]; /* Found a bigger number. */ ? } ? printf ("the max is %d ", n_max); ? exit (0); /* This subprocess can quite now too. */ }