#include #include #include #include /* For mode constants */ #include /* For O_* constants */ #include #include #define DEBUG 1 #ifdef DEBUG #define dprintf(format, ...) printf(format, ##__VA_ARGS__) #else #define dprintf(format, ...) (void) 0 #endif #define error(format, ...) do { \ fprintf(stderr, format, ## __VA_ARGS__); \ exit(0); \ } while(0) int plop = 0; int main(int argc, char**argv) { int fd = shm_open("/key", O_CREAT| O_RDWR, 0666); if(fd<0) { error("shm_open failed"); } /* set the size of the shared memory segment */ if(ftruncate(fd, 8192) < 0) { error("ftruncate failed"); } if(fork() == 0 ) { dprintf("[%d] I'm the child process\n", getpid()); /* map the shared memory segment in the current address space */ void* buffer = NULL; if((buffer = mmap((void*)0x20000000, 8192, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) <0) { error("mmap failed"); } dprintf("child process starts working\n"); sleep(5); dprintf("child process stops working\n"); int* ptr = buffer; *ptr = 1; int* ptr2 = ptr + 1; dprintf("child process starts waiting\n"); while(*ptr2 == 0) { /* do nothing */ } dprintf("child process stops waiting\n"); /* unmap the memory region */ if(munmap(buffer, 8192) < 0) { error("munmap failed"); } /* close the shared memory segment */ if(close(fd) < 0){ error("close failed"); } } else { dprintf("[%d] I'm the parent process\n", getpid()); /* map the shared memory segment in the current address space */ void* buffer = NULL; if((buffer = mmap((void*)0x10000000, 8192, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) <0) { error("mmap failed"); } int* ptr = buffer; dprintf("parent process starts waiting\n"); while(*ptr == 0) { /* do nothing */ } dprintf("parent process stops waiting\n"); sleep(5); dprintf("parent process notifies the child process\n"); int* ptr2 = ptr + 1; *ptr2 = 1; /* unmap the memory region */ if(munmap(buffer, 8192) < 0) { error("munmap failed"); } /* close the shared memory segment */ if(close(fd) < 0){ error("close failed"); } } int retval = shm_unlink(/key); if(retval<0) { error("shm_unlink failed"); } return EXIT_SUCCESS; }