I'm trying to have two child processes write two random integers to a shared memory, then have the parent read them. I cant seem to validate the writing as I get a segmentation fault whenever I try to access an array element in the parent process.
Trying to read from memory in child process right after writing does nothing.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(){
srand(time(NULL));
int pid2;
key_t key = 12345;
int shmid = shmget(key, 2 * sizeof(int), IPC_CREAT|IPC_EXCL|0666);
int *array = (int *)shmat(shmid, 0, 0);
int pid1 = fork();
//write first array element
if (pid1 == 0){
int n1 = rand() % 10;
printf("I'm process number 1, my pid is %d and my number is %d\n", getpid(), n1);
array[0] = n1;
return 1;
}
if (pid1 > 0){
int pid2 = fork();
if (pid2 == 0){
//write second array element
int n2 = rand() % 10;
printf("I'm process number 2, my pid is %d and my number is %d\n", getpid(), n2);
array[1] = n2;
return 1;
}
}
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
//segmentation fault happens here
printf("%d\n", array[0]);
return 0;
}
int pid2 = fork();this makespid2a local variable, totally unrelated to the initial declaration ofpid2and the later reference:waitpid(pid2, NULL, 0);This is a serious error that needs to be corrected. Suggest: replacing:int pid2 = fork();withpid2 = fork();so it uses the 'function scope' variable instance rather than a variable that is only visible within the current code block - user3629249shmdt()to detach the shared memory that was attached viashmat()- user3629249fork()has 3 different returned values: The code is failing to check for a returned value that is <0, so the code (currently) acts as if the call(s) tofork()were always successful. That is a very risky assumption that the code should NOT make - user3629249