I. Shared Memory in Unix Using C Programming

Shared Memory Example

/*Shared Memory Example In C */

#include<sys/ipc.h>
#include<sys/sem.h>
int main() {
 int id, semid, count = 0, i = 1, j;
 int *ptr;
 id = shmget(8078, sizeof (int), IPC_CREAT | 0666);
 ptr = (int *) shmat(id, NULL, 0);

 union semun {
   int val;
   struct semid_ds *buf;
   ushort *array;
 } u;
 struct sembuf sem;
 semid = semget(1011, 1, IPC_CREAT | 0666);
 ushort a[1] = {1};
 u.array = a;
 semctl(semid, 0, SETALL, u);
 while (1) {
   sem.sem_num = 0;
   sem.sem_op = -1;
   sem.sem_flg = 0;
   semop(semid, &sem, 1);
   *ptr = *ptr + 1;
   printf("process id:%d countis :%d \n", getpid(), *ptr);
   for (j = 1; j <= 1000000; j++) {
    sem.sem_num = 0;
    sem.sem_op = +1;
    sem.sem_flg = 0;
    semop(semid, &sem, 1);
   }
 }
 shmdt(ptr);
}

Sample Output:


SHARED MEMORY
#include<sys/ipc.h>
#include<sys/sem.h>
int main()
{
int id,semid,count=0,i=1,j;
int *ptr;
id=shmget(8078,sizeof(int),IPC_CREAT|0666);
ptr=(int *)shmat(id,NULL,0);
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
}u;
struct sembuf sem;
semid=semget(1011,1,IPC_CREAT|0666);
ushort a[1]={1};
u.array=a;
semctl(semid,0,SETALL,u);
while(1)
{
sem.sem_num=0;
sem.sem_op=-1;
sem.sem_flg=0;
semop(semid,&sem,1);
*ptr=*ptr+1;
printf("process id:%d countis :%d \n",getpid(),*ptr);
for(j=1;j<=1000000;j++)
{
sem.sem_num=0;
sem.sem_op=+1;
sem.sem_flg=0;
semop(semid,&sem,1);
}
}
shmdt(ptr);

}
OUTPUT
$./sd
process id:4568 countis :1012310 
process id:4568 countis :1012311 
process id:4568 countis :1012312 
process id:4568 countis :1012313 
process id:4568 countis :1012315 
process id:4568 countis :1012317 
process id:4568 countis :1012319 
process id:4568 countis :1012321 

$ ./sd
process id:4607 countis :1012322 
process id:4607 countis :1012324 
process id:4607 countis :1012326 
process id:4607 countis :1012328 
process id:4607 countis :1012330 
process id:4607 countis :1012332 
process id:4607 countis :1012334