Thread: Posix shared memory

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    2

    Posix shared memory

    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;
    }
    Last edited by rutledmj; 10-04-2009 at 02:19 PM.

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    For starters, the order of the arguments to shmget() is incorrect.

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    2
    thats how they are explained in my text book.

    shmget(shared_memory_identifier, shared_memory_size, shared_memory_mode)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Partly shared memory
    By DrSnuggles in forum C++ Programming
    Replies: 13
    Last Post: 01-21-2009, 03:35 AM
  2. Shared Memory semaphores?
    By Ironic in forum C Programming
    Replies: 0
    Last Post: 10-31-2008, 07:13 PM
  3. Shared memory woes
    By joshdick in forum C Programming
    Replies: 4
    Last Post: 07-28-2005, 08:59 AM
  4. Managing shared memory lookups
    By clancyPC in forum Linux Programming
    Replies: 0
    Last Post: 10-08-2003, 04:44 AM
  5. Shared memory in Linux: B-TREE of structures
    By zahid in forum Linux Programming
    Replies: 3
    Last Post: 01-26-2002, 11:15 PM