From fc1ceaee8e26d435a038e77ec1b414e37d618078 Mon Sep 17 00:00:00 2001 From: yuchen Date: Mon, 11 May 2015 12:53:02 +0800 Subject: [PATCH] add share memory examples --- related_info/lab7/ipc/shmem/shmem_client.c | 64 ++++++++++++++++++++++ related_info/lab7/ipc/shmem/shmem_server.c | 62 +++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 related_info/lab7/ipc/shmem/shmem_client.c create mode 100644 related_info/lab7/ipc/shmem/shmem_server.c diff --git a/related_info/lab7/ipc/shmem/shmem_client.c b/related_info/lab7/ipc/shmem/shmem_client.c new file mode 100644 index 0000000..53e8fe4 --- /dev/null +++ b/related_info/lab7/ipc/shmem/shmem_client.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#include +#include + +#define SHMSZ 1024 + +main() +{ + int shmid; + key_t key; + char *shm, *s; + + /* + * We need to get the segment named + * "1234", created by the server. + */ + key = 1234; + + /* + * Locate the segment. + */ + if ((shmid = shmget(key, SHMSZ, 0666)) < 0) { + perror("shmget"); + return 1; + } + + /* + * Now we attach the segment to our data space. + */ + if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { + perror("shmat"); + return 1; + } + + /* + * Zero out memory segment + */ + memset(shm,0,SHMSZ); + s = shm; + + /* + * Client writes user input character to memory + * for server to read. + */ + for(;;){ + char tmp = getchar(); + // Eat the enter key + getchar(); + + if(tmp == 'q'){ + *shm = 'q'; + break; + } + *shm = tmp; + } + + if(shmdt(shm) != 0) + fprintf(stderr, "Could not close memory segment.\n"); + + return 0; +} diff --git a/related_info/lab7/ipc/shmem/shmem_server.c b/related_info/lab7/ipc/shmem/shmem_server.c new file mode 100644 index 0000000..8759c1e --- /dev/null +++ b/related_info/lab7/ipc/shmem/shmem_server.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include + +#define SHMSZ 1024 + +main(int argc, char **argv) +{ + char c, tmp; + int shmid; + key_t key; + char *shm, *s; + + /* + * Shared memory segment at 1234 + * "1234". + */ + key = 1234; + + /* + * Create the segment and set permissions. + */ + if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { + perror("shmget"); + return 1; + } + + /* + * Now we attach the segment to our data space. + */ + if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { + perror("shmat"); + return 1; + } + + /* + * Zero out memory segment + */ + memset(shm,0,SHMSZ); + s = shm; + + /* + * Read user input from client code and tell + * the user what was written. + */ + while (*shm != 'q'){ + sleep(1); + if(tmp == *shm) + continue; + + fprintf(stdout, "You pressed %c\n",*shm); + tmp = *shm; + } + + if(shmdt(shm) != 0) + fprintf(stderr, "Could not close memory segment.\n"); + + return 0; +}