Skip to content

Instantly share code, notes, and snippets.

@runzhen runzhen/get.c
Created Sep 6, 2018

Embed
What would you like to do?
share-memory
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define STORAGE_ID "/SHM_TEST"
#define STORAGE_SIZE sizeof(int)
int main(int argc, char *argv[])
{
int res, fd;
pid_t pid;
void *addr;
pid = getpid();
// get shared memory file descriptor (NOT a file)
fd = shm_open(STORAGE_ID, O_RDONLY, S_IRUSR | S_IWUSR);
if (fd == -1) {
return -1;
}
// map shared memory to process address space
addr = mmap(NULL, STORAGE_SIZE, PROT_READ, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
return -1;
}
// place data into memory
printf("./GET pid %d: Read from shared memory: %d\n", pid, *(int*)addr);
return 0;
}
#!/bin/bash
SET="set"
GET="get"
CFLAGS="-lrt"
gcc -o ${SET} ${SET}.c ${CFLAGS}
gcc -o ${GET} ${GET}.c ${CFLAGS}
./${SET} &
./${SET} &
./${SET} &
./${SET} &
./${SET} &
./${SET} &
./${SET} &
sleep 1
./${GET}
sleep 1
rm ${SET} ${GET}
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define STORAGE_ID "/SHM_TEST"
#define STORAGE_SIZE sizeof(int)
int main(int argc, char *argv[])
{
int res, fd, len;
pid_t pid;
void *addr;
// get shared memory file descriptor (NOT a file)
fd = shm_open(STORAGE_ID, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
return -1;
}
// extend shared memory object as by default it's initialized with size 0
res = ftruncate(fd, sizeof(int));
if (res == -1) {
return -1;
}
// map shared memory to process address space
addr = mmap(NULL, STORAGE_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
return -1;
}
for (int i = 0; i < 10000; i++) {
*(int *)addr = *(int *)addr + 1;
}
// wait for someone to read it
sleep(2);
// mmap cleanup
res = munmap(addr, STORAGE_SIZE);
if (res == -1) {
return -1;
}
// shm_open cleanup
fd = shm_unlink(STORAGE_ID);
if (fd == -1) {
return -1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.