Skip to content

Instantly share code, notes, and snippets.

@srsandy
Last active January 22, 2024 00:52
Show Gist options
  • Save srsandy/fd043a0440262735a3d9fd628fe3f658 to your computer and use it in GitHub Desktop.
Save srsandy/fd043a0440262735a3d9fd628fe3f658 to your computer and use it in GitHub Desktop.
Store an Array in shared memory c
// write.c
#include<stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main(int argc, char const *argv[]) {
int key = ftok(".", 34);
int *arr;
int shmid = shmget(key,sizeof(int)*5,0666|IPC_CREAT);
arr = (int *)shmat(shmid, NULL, 0);
int i;
for(i=0; i<5; i++)
arr[i] = i*3;
for(i=0; i<5; i++)
printf("%d\n", arr[i]);
shmdt((void *) arr);
return 0;
}
//read.c
#include<stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
int main(int argc, char const *argv[]) {
int key = ftok(".", 34);
int *arr;
int shmid = shmget(key,sizeof(int)*5,0666|IPC_EXCL);
arr = shmat(shmid, NULL, 0);
int i;
for(i=0; i<5; i++)
printf("%d\n", arr[i] );
shmdt((void *) arr);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment