Part A-5

 Lab pgm:5

Write a program to create an integer variable using shared memory concept and increment the variable simultaneously by two processes. Use semaphores to avoid race conditions

#include <sys/types.h>

#include<sys/ipc.h>

#include <sys/shm.h>

#include <unistd.h>

#include <string.h>

#include <errno.h>


int main(void) {


   pid_t pid;

   int *shared;

   int shmid;


   shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);

   printf("shared Memory ID = %u",shmid);

   if (fork() ==0) {

       shared = shmat(shmid, (void *) 0, 0);

       printf("child pointer %u \n", shared);

       *shared=1;

       printf("child value=%d \n", *shared);

       sleep(2);

       printf("child value=%d \n", *shared);


      } else {

              shared = shmat(shmid, (void *)0, 0);

              printf("parent pointer %u \n", shared);

              printf("parent value=%d \n", *shared);

              sleep(1);

              *shared=42;

              printf("parent value=%d \n", *shared);

              sleep(5);

              shmctl(shmid, IPC_RMID, 0);

          }

      }


 


Comments