Skip to content

Instantly share code, notes, and snippets.

@yangsheng1107
Created December 25, 2015 05:56
Show Gist options
  • Select an option

  • Save yangsheng1107/cb739e7f005150cc3f04 to your computer and use it in GitHub Desktop.

Select an option

Save yangsheng1107/cb739e7f005150cc3f04 to your computer and use it in GitHub Desktop.
sample to use posix shared memory
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/mman.h>
// http://man7.org/tlpi/code/online/dist/mmap/anon_mmap.c
//#define USE_MAP_ANON
//#define USE_MAP_SHARED_WITH_OPEN
#define USE_MAP_SHARED_WITH_SHM_OPEN
int main(int argc, char *argv[])
{
void *addr; /* Pointer to shared memory region */
pid_t cpid = 0;
int buffer_size = 4 * 1024;
#ifdef USE_MAP_ANON /* Use MAP_ANONYMOUS */
addr = mmap(NULL, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED)
{
perror("mmap");
exit(-1);
}
#endif
#ifdef USE_MAP_SHARED_WITH_OPEN
int fd = open("/dev/zero", O_RDWR); /* map to "/dev/zero"*/
if (fd == -1)
{
perror("open");
}
addr = mmap(NULL, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED)
{
perror("mmap");
close(fd);
exit(-1);
}
if (close(fd) == -1) /* No longer needed */
{
munmap(addr, buffer_size);
shm_unlink("/dev/zero");
perror("close");
exit(-1);
}
#endif
#ifdef USE_MAP_SHARED_WITH_SHM_OPEN
int fd = shm_open("/shmname", O_CREAT | O_RDWR, 0666); /* map to "/dev/zero"*/
if (fd == -1)
{
perror("open");
exit(-1);
}
if (ftruncate(fd, buffer_size) < 0)
{
perror("ftruncate");
close(fd);
exit(-1);
}
addr = mmap(NULL, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED)
{
perror("mmap");
close(fd);
exit(-1);
}
if (close(fd) == -1) /* No longer needed */
{
munmap(addr, buffer_size);
shm_unlink("/dev/zero");
perror("close");
exit(-1);
}
#endif
cpid = fork();
if (cpid < 0)
{
perror("fork");
}
else if (cpid == 0)
{
printf("child pid is %d\n", getpid());
sprintf((char *)addr, "Hello world !!");
}
else
{
printf("parent pid is %d and child pid is %d\n", getpid(), cpid);
wait(0);
printf("Get : %s\r\n", (char *)addr);
}
if (addr > 0)
{
munmap(addr, buffer_size);
}
#ifdef USE_MAP_SHARED_WITH_OPEN
shm_unlink("/dev/zero");
#endif
#ifdef USE_MAP_SHARED_WITH_SHM_OPEN
shm_unlink("/shmname");
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment