Hello! I'm trying to learn how to use shared memory, so I wrote a simple program to exchange an integer value between a parent process and its child.
The problem is that the program doesn't work, because regardless of the number that I write into the shared memory the child always reads 0. This is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/shm.h>
sig_atomic_t flag = 0;
void handler(int signum){
flag = 1;
}
int main(){
int key, num;
int *mem;
pid_t childpid;
key = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
mem = (int*) shmat(key, 0, 0);
signal(SIGUSR1, handler);
printf("Write an integer and press enter...\n");
scanf("%d", &num);
childpid = fork();
if(childpid == 0){
while(!flag) sleep(1);
printf("I'm the child. I've been awakened. Retrieving the number.\n");
printf("The number is %d\n", *mem);
} else {
printf("I'm the father, I received the number %d. I write it in the shared memory.\n", num);
mem = #
printf("I'm awaking the child.\n");
kill(childpid, SIGUSR1);
}
shmdt(mem);
shmctl(key, IPC_RMID, 0);
return 0;
}
Someone can help me to find the error and explain me why it's wrong?
Thanks in advance for any help!