Skip to content

Instantly share code, notes, and snippets.

@juniorprincewang
Forked from garcia556/get.c
Last active March 21, 2022 23:30
Show Gist options
  • Save juniorprincewang/16cb7e8f9fd51dc5857b00580dab9b38 to your computer and use it in GitHub Desktop.
Save juniorprincewang/16cb7e8f9fd51dc5857b00580dab9b38 to your computer and use it in GitHub Desktop.
POSIX shared memory IPC example (shm_open, mmap), working on Linux
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define STORAGE_ID "/SHM_TEST"
#define STORAGE_SIZE 32
int main(int argc, char *argv[])
{
int res;
int fd;
char data[STORAGE_SIZE];
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)
{
perror("open");
return 10;
}
// 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 30;
}
// place data into memory
memcpy(data, addr, STORAGE_SIZE);
printf("PID %d: Read from shared memory: \"%s\"\n", pid, data);
return 0;
}
#!/bin/bash
SET="set"
GET="get"
CFLAGS="-lrt"
cc ${CFLAGS} -o ${SET} ${SET}.c
cc ${CFLAGS} -o ${GET} ${GET}.c
./${SET} &
sleep 1
./${GET}
echo "/dev/shm:"
ls -l /dev/shm
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 32
#define DATA "Hello, World! From PID %d"
int main(int argc, char *argv[])
{
int res;
int fd;
int len;
pid_t pid;
void *addr;
char data[STORAGE_SIZE];
pid = getpid();
sprintf(data, DATA, pid);
// get shared memory file descriptor (NOT a file)
fd = shm_open(STORAGE_ID, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1)
{
perror("open");
return 10;
}
// extend shared memory object as by default it's initialized with size 0
res = ftruncate(fd, STORAGE_SIZE);
if (res == -1)
{
perror("ftruncate");
return 20;
}
// map shared memory to process address space
addr = mmap(NULL, STORAGE_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED)
{
perror("mmap");
return 30;
}
// place data into memory
len = strlen(data) + 1;
memcpy(addr, data, len);
// wait for someone to read it
sleep(2);
// mmap cleanup
res = munmap(addr, STORAGE_SIZE);
if (res == -1)
{
perror("munmap");
return 40;
}
// shm_open cleanup
fd = shm_unlink(STORAGE_ID);
if (fd == -1)
{
perror("unlink");
return 100;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment