Skip to content

Instantly share code, notes, and snippets.

@coenraadhuman
Created March 11, 2019 04:40
Show Gist options
  • Save coenraadhuman/f33db454669d455046cb3d01a41f02b9 to your computer and use it in GitHub Desktop.
Save coenraadhuman/f33db454669d455046cb3d01a41f02b9 to your computer and use it in GitHub Desktop.
Slightly modified code from GeeksforGeeks https://www.geeksforgeeks.org/ipc-shared-memory
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
printf("Data read from memory: %s\n",str);
//detach from shared memory
shmdt(str);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
cout << "Write Data : ";
cin >> str; // read word from stdin
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment