Friday, October 18, 2013

UNIX Shared Memory Implementation

-Shared Memory Allows two unrelated processes to access the same memory.
-Shared memory is created by one process and appears to other processes by attach.
-If one process writes to shared memory, the changes immediately visible to any
other process that has access to shared memory.
-Shared Memory provides no synchronization.


Header files to include: <sys/types.h> ,<sys/ipc.h>, <sys/shm.h> <unistd.h>

Creating Shared Memory:
int shmget (key_t key, size_t size, int shmflg);
- Key: unique identification to memory
- Size: of shared memory
- Shmflg: IPC_CREAT | WR permissions, IPC_PRIVATE
- Returns:On Success: shmid On failure: -1


Attaching Shared Memory:
void * shmat(int shmid, void * shmaddr, int shmflg)
– Shmid: returned by shmget
– Shmaddr: shared memory segment address (normally NULL)
– Shmflg : SHM_RDONLY, SHM_RND
- Returns: on success: attached address, on failure: (void*)-1


Detaching Shared Memory:
int shmdt (void *shmaddr)
– Shmaddr: address returned by shmat
- Returns: on success: 0 on failure: -1


Removing Shared Memory:
Shmctl(int shm_id, int cmd, struct shmid_ds *buf)
- shm_id: returned by shmget
- cmd: command to control shared memory ex: for remove IPC_RMID
- Returns: on success:0 On failure:-1


/* Shared Memory implementation */


/* FileName: SMServer.c */

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

#define MAXSIZE  100

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

    key = 1234;

     // Creating shared memory  
     if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
        {
           printf("Error in creating shared memory \n");
           exit(0);
        }
     else
         printf("Shared Memory Created with id %d\n", shmid);
    // Attaching shared memory to this process

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory \n");
        }
     else
        printf("Shared memory attached \n");

    s = shm;

   // Writing data on shared memory
   printf("\nEnter a message to add to message queue: ");
   scanf("%[^\n]s",s);
   getchar();
   printf("Entered message now available on Shared memory \n");

   // Deleting shared memory
   //if(shmctl(shmid, IPC_RMID, 0)==0)
     //printf("Shared memory deleted\n");

    exit(0);
}

To Run: gcc  SMServer.c
              ./a.out




/* FileName: SMClient.c */


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

#define MAXSIZE  100

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

    key = 1234;

    if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
        {
           printf("Error in accessing shared memory \n");
           exit(0);
        }
        else
        {
           printf("Accessing shared memory od id %d\n", shmid);
        }

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory\n");
        }
    else
        {
           printf("Shared Memory Attached \n");
        }

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

   if(shmdt(shm)==0)
     {
         printf("Shared memory detached\n"); 
        
     }
    exit(0);
}

To Run: gcc  SMClient.c
              ./a.out


Mapping & Unmapping a XWindow

XMapWindow(Display*, Window) - is used to map(visible) a Xwindow on top of all window.

XUnmapWindow(Display*, Window) - is used to unmap(hime) a Xwindow.

/* CPP program to map & unmap a Xwindow */
/* FileName: MapUnMap.cpp */


#include<X11/Xlib.h>
#include<assert.h> 
#include<unistd.h>
#include<iostream>
#include<stdio.h>
#define NIL (0)

int main()
{

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));


      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      XSelectInput(dpy, w, StructureNotifyMask);

      XMapWindow(dpy, w);
      sleep(2);
      printf( "Mapping : : 0x%x\n", (unsigned int)w);
      int count=1;
           
      GC gc = XCreateGC(dpy, w, 0, NIL);
      XSetForeground(dpy, gc, whiteColor);

      XEvent event;

      while ( 1 ) {
        XNextEvent( dpy, &event );
        if ( event.type == MapNotify ) {
            XMapEvent *mapevent = (XMapEvent *)&event;
            printf( "UnMapping    : 0x%x\n", (unsigned int)(mapevent->window) );
            ++count;
            XUnmapWindow(dpy, w);
            sleep(2);
        }

    if ( event.type == UnmapNotify ) {
            XUnmapEvent *unmapwindowevent = (XUnmapEvent *)&event;
            printf( "Mapping : 0x%x\n", (unsigned int)(unmapwindowevent->window) );
            ++count;
            XMapWindow(dpy, w);
            sleep(2);
        }
           if(count==10)
              break;
    }

      XFlush(dpy);
      sleep(3);
      return 0;
}



To Run: g++ MapUnMap.cpp -lX11

               ./a.out