Skip to content

Instantly share code, notes, and snippets.

@sondnm
Created April 10, 2020 18:09
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 sondnm/560b9ca988a72bd0fc9d0d0d5dc6143b to your computer and use it in GitHub Desktop.
Save sondnm/560b9ca988a72bd0fc9d0d0d5dc6143b to your computer and use it in GitHub Desktop.
POSIX shared memory demo
// Eg: shm_open_get // => "Hello"
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#define SHM_NAME "shm_open_demo"
#define SHM_SIZE 1024
int main(int argc, const char *argv[])
{
int fd;
char *addr;
struct stat st;
if (argc >= 2) {
fprintf(stderr, "usage: shm_open_get\n");
exit(1);
}
fd = shm_open(SHM_NAME, O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("shm_open");
exit(1);
}
if (fstat(fd, &st) != -1 && st.st_size == 0) {
if (ftruncate(fd, SHM_SIZE) == -1) {
perror("ftruncate");
exit(1);
}
}
addr = mmap(NULL, SHM_SIZE, PROT_READ, MAP_SHARED, fd, 0);
printf("segment contains: \"%s\"\n", addr);
if (munmap(addr, SHM_SIZE) == -1) {
perror("munmap");
exit(1);
}
if (shm_unlink(SHM_NAME) == -1) {
perror("shm_unlink");
exit(1);
}
return 0;
}
// Eg: shm_open_set "Hello"
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#define SHM_NAME "shm_open_demo"
#define SHM_SIZE 1024
int main(int argc, const char *argv[])
{
int fd;
char *addr;
struct stat st;
if (argc < 2) {
fprintf(stderr, "usage: shm_open_set [data to write]\n");
exit(1);
}
fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("shm_open");
exit(1);
}
if (fstat(fd, &st) != -1 && st.st_size == 0) {
if (ftruncate(fd, SHM_SIZE) == -1) {
perror("ftruncate");
exit(1);
}
}
addr = mmap(NULL, SHM_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
printf("Writing to segment: \"%s\"\n", argv[1]);
strncpy(addr, argv[1], SHM_SIZE - 1);
if (munmap(addr, SHM_SIZE) == -1) {
perror("munmap");
exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment