Click here to Skip to main content
14,207,068 members

Linux shared memory. Sending multiple messages.

shihappns asked:

Open original thread
This program generate two messages in shared memory. What I want is messages to store different data. When I run this program 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?

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

int main() 
    // 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); 

    // 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; 

What I have tried:

I tried to use different keys, different shmid 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.
Tags: C, Linux, memory, program


When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).

Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190612.1 | Last Updated 26 Mar 2009
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100