Skip to content

Instantly share code, notes, and snippets.

@figengungor
Created October 24, 2013 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save figengungor/7139062 to your computer and use it in GitHub Desktop.
Save figengungor/7139062 to your computer and use it in GitHub Desktop.
Shared Memory in C (Linux)
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/shm.h>
int main()
{
char* shared_memory;
int segment_id;
const int size = 4096; //byte
//allocates shared memory segment and return its identifier as an integer
segment_id = shmget(IPC_PRIVATE, size, S_IWUSR | S_IRUSR);
//attaches the shared memory segment to the address space of process and returns the address
shared_memory = (char *) shmat(segment_id, NULL, 0);
//Write operation
sprintf(shared_memory, "In shared Memory \n");
//Read Operation
printf("Reading ---> %s\n", shared_memory);
//detaches the shared memory segment from the address sapce of process
shmdt(shared_memory);
//removes the shared memory segment
shmctl(segment_id, IPC_RMID, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment