-Shared Memory Allows two unrelated processes to access the same memory.
-Shared memory is created by one process and appears to other processes by attach.
-If one process writes to shared memory, the changes immediately visible to any
other process that has access to shared memory.
-Shared Memory provides no synchronization.
Header files to include: <sys/types.h> ,<sys/ipc.h>, <sys/shm.h> <unistd.h>
Creating Shared Memory:
int shmget (key_t key, size_t size, int shmflg);
- Key: unique identification to memory
- Size: of shared memory
- Shmflg: IPC_CREAT | WR permissions, IPC_PRIVATE
- Returns:On Success: shmid On failure: -1
Attaching Shared Memory:
void * shmat(int shmid, void * shmaddr, int shmflg)
– Shmid: returned by shmget
– Shmaddr: shared memory segment address (normally NULL)
– Shmflg : SHM_RDONLY, SHM_RND
- Returns: on success: attached address, on failure: (void*)-1
Detaching Shared Memory:
int shmdt (void *shmaddr)
– Shmaddr: address returned by shmat
- Returns: on success: 0 on failure: -1
Removing Shared Memory:
Shmctl(int shm_id, int cmd, struct shmid_ds *buf)
- shm_id: returned by shmget
- cmd: command to control shared memory ex: for remove IPC_RMID
- Returns: on success:0 On failure:-1
/* Shared Memory implementation */
/* FileName: SMServer.c */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
int main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 1234;
// Creating shared memory
if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
{
printf("Error in creating shared memory \n");
exit(0);
}
else
printf("Shared Memory Created with id %d\n", shmid);
// Attaching shared memory to this process
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
printf("Error in attaching shared memory \n");
}
else
printf("Shared memory attached \n");
s = shm;
// Writing data on shared memory
printf("\nEnter a message to add to message queue: ");
scanf("%[^\n]s",s);
getchar();
printf("Entered message now available on Shared memory \n");
// Deleting shared memory
//if(shmctl(shmid, IPC_RMID, 0)==0)
//printf("Shared memory deleted\n");
exit(0);
}
To Run: gcc SMServer.c
./a.out
/* FileName: SMClient.c */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
int main()
{
int shmid;
key_t key;
char *shm, *s;
key = 1234;
if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
{
printf("Error in accessing shared memory \n");
exit(0);
}
else
{
printf("Accessing shared memory od id %d\n", shmid);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
printf("Error in attaching shared memory\n");
}
else
{
printf("Shared Memory Attached \n");
}
//Now read what the server put in the memory.
for (s = shm; *s != '\0'; s++)
putchar(*s);
putchar('\n');
if(shmdt(shm)==0)
{
printf("Shared memory detached\n");
}
exit(0);
}
To Run: gcc SMClient.c
./a.out
No comments:
Post a Comment