/* This program illustrates mmap with a pair of processes. * A "writer" process sends messages to a "reader" process. * * After you compile this code, you should create a file for it to * use as its shared, mmapped file. Edit a text file, say "mmap.txt", * and put at least 20 characters into it. Then you can run the * program by opening two terminal windows, and typing * * ./23-mmap mmap.txt read * * into one window, and * * ./23-mmap mmap.txt write * * into the other. Then you can begin typing messages into the "write" * process, of length up to 20 characters, to be delivered to the * "read" process. * * SOMETHING TO THINK ABOUT: The reader and writer are accessing * shared memory. Could they ever interfere with each other? How * could you fix it? * * NOTE: Like the code in lecture, this code omits error checks when * calling the various library and system calls. Your MP code should * check for errors. We omit it here so that the main steps of the * code are more clearly illustrated. */ #include #include #include #include #include #include #include #define MMAP_SIZE 20 int main(int argc, char** argv) { int fd; char * shared_mem; fd = open(argv[1], O_RDWR | O_CREAT); shared_mem = mmap(NULL, MMAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); if (!strcmp(argv[2], "read")) { while (1) { printf("%s", shared_mem); sleep(1); } } else while (1) fgets(shared_mem, MMAP_SIZE, stdin); }