Click here to Skip to main content
15,868,141 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() 
{ 
//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; 
}


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

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



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 http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900