Friday, 8 November 2013

C program to demonstrate Client/Server Inter Process Communication using Shared Memory

 [singh@00-13-02-56-15-7c shared_memory]$ vi server.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.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");

    memcpy(shm,"Rajneesh Kumar Singh",25);   


    s = shm;

      s+=25;

    *s=0;

    /*
     * 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);
}



[singh@00-13-02-56-15-7c shared_memory]$ vi client.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);
}



Output :

Note: Use two terminals to generate output for this program.

In 1st Terminal :-
 
[singh@00-13-02-56-15-7c shared_memory]$ cc server.c -o server
[singh@00-13-02-56-15-7c shared_memory]$
./server


In 2nd Terminal :-

[singh@00-13-02-56-15-7c shared_memory]$ cc client.c -o client
[singh@00-13-02-56-15-7c shared_memory]$
./client
Rajneesh Kumar Singh


 

No comments:

Post a Comment