Saturday, March 31, 2012

Shared Memory Program - System Software Lab

Lab Program - 13 - Shared Memory - System Software Lab


#include “sys/types.h”
#include “sys/ipc.h”
#include “sys/shm.h”
#include “stdio.h”

#define SHMSZ     27

main()
{
    char c;
    int shmid;
    key_t key;
    char *shm,*s;  
/* The shared memory is named as 2012 */
    key = 2012;

    if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        exit(1);
    }
    
/* Mapping the Shared Memory */
    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }

    s = shm;
  
/* Storing some text in the Shared Memory */
    for (c = 'a'; c <= 'z'; c++)
        *s++ = c;
    *s = NULL;
/* Wait for the other process that reads the shared memory and alters the content */
    while (*shm != '*')
        sleep(1);

    printf("\n End of the Server Program - Shared Memory");
    exit(0);
}








#include “sys/types.h”
#include “sys/ipc.h”
#include “sys/shm.h”
#include “stdio.h”

#define SHMSZ     27

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

    /*   The shared memory given a name as 2012 */

    key = 2012;

    if ((shmid = shmget(key, SHMSZ, 0666)) < 0) (< = <)
        {
          perror("shmget");
          exit(1);
        }
 /* Map the Shared Memory */   
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
    {
        perror("shmat");
        exit(1);
    }

/* Read the content from the Shared Memory */

    for (s = shm; *s != NULL; s++)
        putchar(*s);
    putchar('\n');

/* Change the first character of the Shared memory to * to indicate the server the content were read */

    *shm = '*';

    printf("\n End of Client Program - Shared Memory");

    exit(0);
}


No comments:

Post a Comment