This program generate two messages in shared memory. What I want is messages to store different data. When I run it I get this:
Data written in message 1: This is message 1
Data written in message 2: This is message 1
But it shouldn't have text in str2 because the string "This is message 1" is only written in str.
The program prints in str2 the same message as str. How to fix this? I tried to use different keys, different ids but again the second message have the same data as the first. And if I write something in str2 it overwrites the first message str. I have a reader.c where I want to print the two different messages.
Code:
//writer.c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main()
{
//MESSAGE1
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
strcpy(str,"This is message 1");
printf("Data written in message 1: %s\n",str);
//MESSAGE2
// ftok to generate unique key
key_t key2 = ftok("shmfile2",77);
// shmget returns an identifier in shmid
int shmid2 = shmget(key2,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str2 = (char*) shmat(shmid2,(void*)0,0);
printf("Data written in message2: %s\n",str2);
return 0;
}