#include #include #include #include #include #include #include #define MAX_LEN 10000 struct region { /* Defines "structure" of shared memory */ int len; char buf[MAX_LEN]; }; struct region *rptr; int fd; int main(int argc, const char *argv[]) { int fd, status; mlockall(MCL_CURRENT|MCL_FUTURE); /* Create shared memory object and set its size */ fd = shm_open("/myregion", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { perror("shm_open"); exit(EXIT_FAILURE); } if ((status = ftruncate(fd, sizeof(struct region))) == -1) { /* Handle error */; perror("ftruncate"); close(fd); status = EXIT_FAILURE; goto close_and_unlink; } /* Map shared memory object */ rptr = (struct region *) mmap(NULL, sizeof(struct region), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (rptr == MAP_FAILED) { /* Handle error */; perror("mmap"); status = EXIT_FAILURE; goto close_and_unlink; } /* Now we can refer to mapped region using fields of rptr; for example, rptr->len */ sleep(1); munmap(rptr, sizeof(struct region)); close_and_unlink: close(fd); shm_unlink("/myregion"); return status; }