#include <stdio.h> #include <semaphore.h> #include <sys/ipc.h> #include <sys/shm.h> #define PATHNAME "/tmp/.what_the_hell_is_this" typedef struct Item { sem_t full, empty; int data; } Item; void sys_err(const char* msg); int main() { key_t key; pid_t pid; int shmid; Item* addr; /* remove a shared memory segment from the system */ key = ftok(PATHNAME, 1); if (key == -1) sys_err("ftok"); shmid = shmget(key, 0, SHM_R|SHM_W); shmctl(shmid, IPC_RMID, NULL); /* create a new shared memory segment */ shmid = shmget(key, sizeof(Item), IPC_CREAT|IPC_EXCL|SHM_W|SHM_R); if (shmid == -1) sys_err("shmget"); addr = (Item*)shmat(shmid, NULL, 0); if (addr == (Item*)-1) sys_err("shmat"); /* initialize addr */ sem_init(&addr->full, 1, 0); sem_init(&addr->empty, 1, 1); shmdt(addr); pid = fork(); if (pid > 0) { /* parent for writing */ shmid = shmget(key, 0, SHM_W); if (shmid == -1) sys_err("parent shmget"); addr = (Item*)shmat(shmid, NULL, 0); if (addr == (Item*)-1) sys_err("parent shmat"); while (1) { sem_wait(&addr->empty); fprintf(stdout, "parent: "); fscanf(stdin, "%d", &addr->data); sem_post(&addr->full); } } else if (pid == 0) { /* child for reading */ shmid = shmget(key, 0, SHM_R); if (shmid == -1) sys_err("child shmget"); addr = (Item*)shmat(shmid, NULL, 0); if (addr == (Item*)-1) sys_err("child shmat"); while (1) { sem_wait(&addr->full); fprintf(stdout, "child: %d\n", addr->data); sem_post(&addr->empty); } } else { sys_err("fork"); } return 0; } void sys_err(const char* msg) { perror(msg); exit(0); } |
chao@chao-laptop:~/c-study/cu$ cat shmread.c #include <stdio.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/ipc.h> #include <errno.h> #define BUF_SIZE 1024 #define MYKEY 24 int main() { int shmid; char * shmptr; key_t key; if (( key = ftok(".", MYKEY)) == -1) { perror("ftok error!\n"); return -1; } if (( shmid = shmget(key, BUF_SIZE, IPC_CREAT | 0666)) == -1) { perror("shmget error!\n"); return -1; } if (( shmptr = shmat(shmid, 0, 0)) == (void *)-1) { perror("shmat error!\n"); return -1; } while(1) { printf("string: %s\n", shmptr); while(*shmptr != '\0') shmptr++; sleep(3); } return 0; } chao@chao-laptop:~/c-study/cu$ cat shmwrite.c #include <stdio.h> #include <sys/shm.h> #include <sys/ipc.h> #include <sys/sem.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #define BUF_SIZE 1024 #define MYKEY 24 int main() { int shmid; char * shmptr; key_t key; if(( key = ftok(".", MYKEY)) == -1) { perror("ftok error\n"); return -1; } if (( shmid = shmget(key, BUF_SIZE, IPC_CREAT | 0666)) == -1) { perror("shmget error\n"); return -1; } if (( shmptr = shmat(shmid, 0, 0)) == (void *)-1) { perror("shmat error\n"); return -1; } while(1) { printf("writer: "); fgets(shmptr, BUF_SIZE, stdin); while(*shmptr != '\n') shmptr++; *shmptr = '\0'; //getchar(); } exit(0); } |
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) | Powered by Discuz! X3.2 |