Monday, March 19, 2012
4:41 PM

Inter process communication using shared memory

Processes can communicate between each other in various ways, one of the techniques is by using shared memory, i.e. the processes share a memory region between each other which both can read from. Processes can read and write from this memory what ever that has to be shared.

To create or get access to an already created shared memory we use the function shmget (shared memory get).



Arguments: key : The key used by the process to identify the shared memory, it is assigned by the process and the other processes which want to communicate with this shared memory need to know this key.

size: The size of the shared memory that is allocated.

flag: If the shared memory is being created then we can use the flag IPC_CREAT as the flag. If we are trying the get access to a shared memory already created then we can pass the mode flag specifying the rights for owner,group and the world in the same format as followed by "chmod".

Return : An identifier to the shared memory which is used along with the "key" to identify the memory segment for communication.

Once the share memory is allocated to start the communication we need forts attach this shard memory with the memory of the process to this we use the function shmat (shared memory attach)



Arguments:

shmid: The identifier returned by shmget

shmaddr: The address where the segment should get attached, if left NULL the system automatically chooses a suitable location for the attach.

shmflg: Used in the specific case when mapping of the segment should replace any existing mapping in the range starting at shmaddr , can be left NULL otherwise.

Return: The address of the shared memory that was attached to the process.

Once the memory segment is attached data can be read from and written to the shared memory using the address returned by shmat and the the functions sscanf and sprintf respectively.

Example:

The following program creates a shared memory in the default mode and then writes a message in the shard memory.

Note the used of IPC_CREAT flag with the shmget call.

write_shm.c



The following code tries access the shared memory created by the above code and read the data written in it. Note that the value of key used by both the codes are same, failing which the shmget will be unable to identify the shared memory.

read_shm.c



Compile the above programs



execute them



You should see the message written by the first process displayed by the second process thus achieving the required communication between the processes.

0 comments:

Post a Comment