// man ftruncate // pass any message between two processes using shared memory #include #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { srandom(time(NULL)); const char *memory_name = "/memory"; char message[] = "Hello there"; int fd = shm_open(memory_name, O_CREAT | O_RDWR, 0777); if (fd < 0) { fprintf(stderr, "shm_open: "); exit(EXIT_FAILURE); } printf("Shred memory file descriptor: %d\n", fd); if (ftruncate(fd, sizeof(message)) < 0) { fprintf(stderr, "ftruncate: \n"); exit(EXIT_FAILURE); } pid_t pid; pid = fork(); if (pid == -1) { perror("fork: "); exit(EXIT_FAILURE); } if (pid == 0) { char *addr = mmap(NULL, sizeof(message), PROT_READ, MAP_SHARED, fd, 0); printf("Value: %s\n", addr); if (addr == MAP_FAILED) { fprintf(stderr, "mmap: "); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } char *addr = mmap(NULL, sizeof(message), PROT_WRITE, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) { fprintf(stderr, "mmap: "); exit(EXIT_FAILURE); } strcpy(addr, message); shm_unlink(memory_name); int status; wait(&status); munmap(addr, sizeof(message)); return 0; }