Sunday 3 July 2016

Linux Shared Memory C | shmget Example

Linux Shared Memory C | shmget Example

Description: Following c language program is a Linux shared memory example. This is useful in understanding Linux IPC (Inter process communication). The command/function that is used in this code and can be used in doing shared memory programming is shmget()


#include<stdio.h>
#include<sys/shm.h>
#include<sys/stat.h>
#include<unistd.h>

int count=1;

int main(){

    int segment_id_1,segment_id_2;
    char *shared_memory_1,*shared_memory_2;
    struct shmid_ds shmbuffer;
    int segment_size;
    const int shared_segment_size=0x6400;

    /*Allocate a shared memory segment*/
   
    segment_id_1=shmget (IPC_PRIVATE,shared_segment_size,IPC_CREAT|    IPC_EXCL|S_IRUSR|S_IWUSR);

    segment_id_2=shmget (IPC_PRIVATE,shared_segment_size,IPC_CREAT|    IPC_EXCL|S_IRUSR|S_IWUSR);

    /*Attach the shared memory segment*/

    shared_memory_1=(char*)shmat(segment_id_1,0,0);
    shared_memory_2=(char*)shmat(segment_id_2,0,0);
   
    pid_t pid;
    pid=fork();

    if(pid>0){

       /*Write a string to the shared memory segment*/
       sprintf(shared_memory_1,"Hello Child.");
      
       wait(NULL);

       /*Print out the string from shared memory*/
       printf("Message for Parent: %s\n",shared_memory_2);

       pid_t pid;
       pid=fork();

       if(pid>0){
           wait(NULL);
           printf("Message for Parent: %s\n",shared_memory_2);
           pid_t pid;
           pid=fork();  

           if(pid>0){
              wait(NULL);
              printf("Message for Parent: %s\n",shared_memory_2);
           }
           else if(pid==0){

              /*Print out the string from shared memory*/
              printf("Message for Child#3: %s\n",shared_memory_1);
             
              /*Write a string to the shared memory segment*/
              sprintf(shared_memory_2,"Hello Parent from Chid#3");
      
           }  
       }
       else if(pid==0){

           /*Print out the string from shared memory*/
           printf("Message for Child#2: %s\n",shared_memory_1);
      
           /*Write a string to the shared memory segment*/
           sprintf(shared_memory_2,"Hello Parent from Child#2");
       }                
    }
      
    else if(pid==0){
     
       /*Print out the string from shared memory*/
       printf("Message for Child#1: %s\n",shared_memory_1);
      
       /*Write a string to the shared memory segment*/
       sprintf(shared_memory_2,"Hello Parent from Child#1");
    }
    return 0;
}

No comments

Post a Comment

Recent Posts