#include <stdio.
h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<string.h>
#define SHM_SIZE 1024
int main() {
key_t key = ftok("shmfile", 65); // Generate unique key
char buff[]="hello world";
int shmid = shmget(key, SHM_SIZE, 0666|IPC_CREAT); // Get shared memory segment
if (shmid == -1) {
perror("shmget");
exit(1);
}
char *data = (char*) shmat(shmid, NULL, 0); // Attach to the shared memory segment
if (data == (char*)(-1)) {
perror("shmat");
exit(1);
}
printf("Data write to shared memory")
strcpy(data,buff);
printf("Data read from shared memory: %s\n", data);
shmdt(data); // Detach from the shared memory segment
shmctl(shmid, IPC_RMID, NULL); // Destroy the shared memory segment
return 0;
}
1. ftok()
key_t ftok()
It is used to generate a unique key.
2. shmget()
int shmget(key_t key,size_t size, int shmflg);
Upon successful completion, shmget() returns an identifier for the shared memory
segment.
3. shmat()
void *shmat(int shmid ,void *shmaddr ,int shmflg);
Before you can use a shared memory segment, you have to attach
yourself to it using shmat().
Here, shmid is a shared memory ID and shmaddr specifies the specific address to
use but we should set it to zero and OS will automatically choose the address.
4. shmdt()
int shmdt(void *shmaddr);
When you’re done with the shared memory segment, your program
should detach itself from it using shmdt().
5. shmctl()
shmctl(int shmid,IPC_RMID,NULL);
When you detach from shared memory, it is not destroyed. So, to
destroy shmctl() is used.