Thread: Putting A Struct Into Shared Memory

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    1

    Putting A Struct Into Shared Memory

    I have an array of structs I'm trying to get into shared memory. This is what I have so far.

    Code:
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    
    typedef struct
    {
      int num;
      int denom;
    } Fraction;
    
    Fraction FracArray[5];
    
    int main()
    {
      key_t key;
      int shmid;
    
      key = 5678;
      shmid = shmget(key, 1024, IPC_CREAT | 0666)
      FracArray[5] = shmat(shmid, NULL, 0);
    
      return 0;
    }
    When compiled I get
    incompatible types when assigning to type ‘Fraction’ from type ‘void *’

    So while trying to find a solution I saw someone mention to try and use pointers and stick that into shared memory so I came up with

    Code:
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    
    typedef struct
    {
      int num;
      int denom;
    } Fraction;
    
    Fraction *FracArray[5];
    
    int main()
    {
      key_t key;
      int shmid;
    
      key = 5678;
      shmid = shmget(key, 1024, IPC_CREAT | 0666);
      FracArray[5] = shmat(shmid, NULL, 0);
    
      printf("test\n");
    
      FracArray[1]->num = 5;
    
      return 0;
    }
    But when I run that program test prints fine but then it seg faults. Can anyone explain which way I should be doing it and how to actually get the struct array into shared memory correctly?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You should have something similar to how you would call malloc.
    Code:
      shmid = shmget(key, 5  * sizeof(Fraction), IPC_CREAT | 0666);
      Fraction *FracArray = shmat(shmid, NULL, 0);
    First you need a sizeof() expression of some sort to say exactly HOW much memory you want.
    Then you need a pointer assignment to be able to get at that memory.

    malloc does all this in one call, but shared memory takes two steps.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Fragmentation with Dynamic FIFO Queue
    By fguy817817 in forum Linux Programming
    Replies: 17
    Last Post: 10-31-2009, 04:17 AM
  2. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  3. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  4. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  5. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM