Featured Post

Trie implementation in C

IPC Shared Memory Implementation in C

A simple Implementation of Shared Memory in C

Shared Memory is a type of IPC where the two processes share same memory chunk and use it for IPC. One process writes into that memory and other reads it.

After running the Server you can see the attached Shared Memory

vgupta80@linux unixprog> ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x0000162e 65537      vgupta80  666        27         1

After running the client the memory is freed.

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x0000162e 65537      vgupta80  666        27         0

//SHMServer.C
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE     27

void die(char *s)
{
    perror(s);
    exit(1);
}

int main()
{
    char c;
    int shmid;
    key_t key;
    char *shm, *s;

    key = 5678;

    if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
        die("shmget");

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        die("shmat");

    /*
     *      * Put some things into the memory for the
     *        other process to read.
     *        */
    s = shm;

    for (c = 'a'; c <= 'z'; c++)
        *s++ = c;


    /*
     * Wait until the other process
     * changes the first character of our memory
     * to '*', indicating that it has read what
     * we put there.
     */
    while (*shm != '*')
        sleep(1);

    exit(0);
}


//SHMClient.C

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE     27

void die(char *s)
{
    perror(s);
    exit(1);
}

int main()
{
    int shmid;
    key_t key;
    char *shm, *s;

    key = 5678;

    if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
        die("shmget");

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        die("shmat");

    //Now read what the server put in the memory.
    for (s = shm; *s != '\0'; s++)
        putchar(*s);
    putchar('\n');

    /*
     *Change the first character of the
     *segment to '*', indicating we have read
     *the segment.
     */
    *shm = '*';

    exit(0);
}

Comments

  1. Thanx buddy. :) Helped me a lot. Your code was fucking awesome.

    ReplyDelete
  2. nice code, but you have a memory leak, how do I release the 27 bytes of shared memory?????

    ReplyDelete
  3. You can use following function to detach the memory :

    int shmdt(void *shmaddr);

    To delete the shared memory, either use ipcrm command from shell or shmctl(shmid, IPC_RMID, NULL) from code.

    ReplyDelete
  4. NIce Chunk of Code....Very useful for Rookies....

    ReplyDelete
  5. Very helpful. Thanks.

    ReplyDelete
  6. Very Useful..Thanks a lot

    ReplyDelete
  7. thankx mate.. its an easy to understand code for beginners..

    ReplyDelete
  8. error: invalid conversion from âvoid*â to âchar*â

    ReplyDelete
    Replies
    1. Compile with gcc not g++

      Delete
    2. I compile with gcc, but It still have an error.
      https://www.facebook.com/photo.php?fbid=1162454227217275&set=a.128158980646810.21042.100003581258395&type=3
      pls help me

      Delete
    3. I still have error
      https://www.facebook.com/photo.php?fbid=1162454227217275&set=a.128158980646810.21042.100003581258395&type=3

      Delete
    4. Please share the error(in text) that you are facing.

      Delete
    5. how to give group of characters in server andalso receive the same group of characters in client output

      Delete
  9. How is synchronization handled here ?

    ReplyDelete
  10. is it posix or systemv semaphore implemented

    ReplyDelete
  11. when iam running program it is saying shmget:function not implemented

    ReplyDelete
    Replies
    1. This error is not related to this program. shmget is a system call. You might want to search about the error.

      Delete
  12. Hi, i'm trying to save a file (2.5MB) in shm but occurs a Segmentation fault (core dumped)

    ReplyDelete
    Replies
    1. Can you check and post the stack trace using gdb on where it is failing ? Normally 2.5 MB is not a big size as shared memory size is quite big.

      Also you can check the available shared memory size using this command:
      cat /proc/sys/kernel/shmall

      Delete
  13. Maybe a very amateur question, could you please explain what these lines of code do:

    key_t key; /* this appears like some kind of variable definition*/

    if ((shmid = shmget(key, MAXSIZE, 0666)) < 0) /* shmget appears like some function, but where is this defined? */

    Thank you for the help :)

    ReplyDelete
  14. shmget is IPC function which returns the identifier of the System V shared memory segment associated with the value of the argument key.

    ReplyDelete
  15. How do I use shared memory by creating structures.

    ReplyDelete
  16. how to code - in client side it should read marks of subject usimg array and in server side it should calculate the average of subject marks and the result should be displayed in client side using shared memory in same way of above program.please help me

    ReplyDelete
  17. My task is to Dry run the the following code and write down the output with explanation.Anyone can do it for me i will be very thankful

    ReplyDelete

Post a Comment

Please post your valuable suggestions