/*A program to write access shared memory & write into it*/
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>//shm.h is header file used for shared memory
int main()
{
int shm_id;
int *ptr1;
void *ptr;//pointer is taken which will be made base address of shared memory accessed...we have written it void type ....we will specify this pointer as int* or float* or char* at run time...bcz many time data to be put into this shared memory is specified on run time.....check which type of data is going to put in that memory..& put that type of data into memory by typecasting
shm_id=shmget(100,8,666|IPC_CREAT);//to access the memory...+ve integer should be same as ...as if memory is made shared memory in any other process & that memory is accessed...2nd arg is count block of memory which we want to access..
printf("\nsemid=%d",shm_id);//shmid is returned
ptr=shmat(shm_id,(int*)0,SHM_RND);//shmat to attach shared memory..SHM_RND is SHM_RDONLY flag
/*A program presents working of shared memory & accessing data alredy written to it..*/
//Shared memory is a commom area of memory which could be accesed in all those files where shmget() & shmat() command is used
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
int main()
{
int key;void* ptr;
int *ptr3;
key=shmget(100,8,666|IPC_CREAT);//shmget will create a shared memory...1st arg is any +ve integer value which will be used to another files also ..through which it returns shmid & in next file identify shared memory....2nd arg is hw many bytes of shared memory is provided.....3rd is PERMISSIONS TO ACCESS THAT SHARED MEMORY|IPC_CREAT is FLAG to create shared memory
printf("\nkey=%d",key);//prints shared memory id at which memory is provided...yet not attached
ptr=shmat(key,(void*)0,0);//shmat is to attach the shared memory..1st arg is shmid..2nd is memory address at which shared memory is to provide..write it (void*)0 & let it decide to the system...3rd arg is shm_flag i.e.SHM_RND if u have accessed shared memory to only read..means SHM_RDONLY...||it is zero ..when it works as read & write by default
printf("\nptr=%p",ptr();//shmat) will return base address of memory which is to be shared..that will be ofvoid*
ptr3=(int*)ptr;//void* ptr type pointer is typecasted by int* & providing base address of that memory to another pointer
printf("ptr=%d",*ptr3);//this pointer can only have int type of value...which i m going to access may be already written some int type values by some other process ...we may now also write data into it