#include /* For O_* constants */ #include #include #include #include #include /* For mode constants */ #include #define DEBUG 1 #define SHM_KEY "/key" #define SHM_SZ 8192 #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 main(int argc, char* *argv) { int fd = shm_open(SHM_KEY, O_CREAT| O_RDWR, 0666); if (fd<0) error("shm_open failed"); /* set the size of the shared memory segment */ if (ftruncate(fd, SHM_SZ) < 0) error("ftruncate failed"); if (fork() == 0 ) { void *buffer = (void *)0x20000000; volatile int *ptr, *ptr2; dprintf("[%d] I'm the child process\n", getpid()); /* map the shared memory segment in the current address space */ if((buffer = mmap(buffer, SHM_SZ, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) <0) error("mmap failed"); dprintf("child process starts working\n"); sleep(10); dprintf("child process stops working\n"); dprintf("child process notifies the parent process\n"); ptr = buffer; *ptr = 1; dprintf("child process starts waiting\n"); ptr2 = ptr + 1; while (*ptr2 == 0); dprintf("child process stops waiting\n"); /* unmap the memory region */ if (munmap(buffer, SHM_SZ) < 0) error("munmap failed"); /* close the shared memory segment */ if (close(fd) < 0) error("close failed"); return 0; } else { void *buffer = (void *)0x10000000; volatile int *ptr, *ptr2; dprintf("[%d] I'm the parent process\n", getpid()); /* map the shared memory segment in the current address space */ if((buffer = mmap(buffer, SHM_SZ, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) <0) error("mmap failed"); dprintf("parent process starts waiting\n"); ptr = buffer; while(*ptr == 0); dprintf("parent process stops waiting\n"); dprintf("parent process starts working\n"); sleep(10); dprintf("parent process stops working\n"); dprintf("parent process notifies the child process\n"); ptr2 = ptr + 1; *ptr2 = 1; /* unmap the memory region */ if (munmap(buffer, SHM_SZ) < 0) error("munmap failed"); /* close the shared memory segment */ if (close(fd) < 0) error("close failed"); } wait(0); if (shm_unlink(SHM_KEY) < 0) error("shm_unlink failed"); return EXIT_SUCCESS; }