I am experimenting with POSIX shared-memory and having trouble writing a program. I would like to make the program fork a child and parent process and have the child write something to shared memory and have the parent print the shared memory. But so far the program doesnt seem to be printing out anything. Can someone tell me whats wrong and how to fix it?
Here is my progress so far:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main()
{
int segment_id;
char *shared_memory;
const int size = 4096;
pid_t pid;
pid = fork();
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
if (pid == 0 )
{
printf("This is the child speaking\n");
shared_memory = (char *) shmat(segment_id, NULL, 0);
sprintf(shared_memory, "Hi there!");
shmdt(shared_memory);
}
else
{
wait(NULL);
printf("This is the parent speaking\n");
shared_memory = (char *) shmat(segment_id, NULL, 0);
printf("%s\n", shared_memory);
shmdt(shared_memory);
}
shmctl(segment_id, IPC_RMID, NULL);
return 0;
}