/**/ /* * shm_test.c * 共享内存测试程序,往一个共享内存里循环写入数据 */ #include < sys / shm.h > #include < sys / types.h > #include < unistd.h > #include < stdio.h > #define SHARED_MEME "/tmp/share" #define SHM_MODE 0600 #include < stdlib.h > int main( void ) ... { key_t key; long shm_id; int i = 0, j; char *ptr; char *back; char name[7] = "Ken Jun"; struct shmid_ds buff; if ((key = ftok(SHARED_MEME, 0)) == -1) printf("ftok error! "); shm_id = shmget(key, 512, SHM_MODE | IPC_CREAT); ptr = shmat(shm_id, 0, 0); shmctl(shm_id, IPC_STAT, &buff); back = ptr; //for (i = 0; i < buff.shm_segsz; i++) while(1) ...{ if (i >= (int)buff.shm_segsz / 7) ...{ ptr = back; i = 0; continue; } printf("在%p内存里", ptr); printf("写入字段%d : ", i); for (j = 0; j < 7; j++) ...{ *ptr = name[j]; printf("%c", *ptr); ptr++; } printf(" . "); usleep(5000); i++; } shmdt(&shm_id); shmctl(shm_id, IPC_RMID, NULL); return 0; } /**/ /* * shm_test_read.c * 共享内存测试程序,从一个共享内存里循环读出数据 */ #include < sys / shm.h > #include < sys / types.h > #include < unistd.h > #include < stdio.h > #define SHARED_MEME "/tmp/share" #define SHM_MODE 0600 int main( void ) ... { key_t key; long shm_id; int i = 0, j; char *ptr; char name[7]; char *back; struct shmid_ds buff; if ((key = ftok(SHARED_MEME, 0)) == -1) printf("ftok error! "); shm_id = shmget(key, 512, SHM_MODE | IPC_CREAT); ptr = shmat(shm_id, 0, 0); shmctl(shm_id, IPC_STAT, &buff); back = ptr; //for (i = 0; i < buff.shm_segsz; i++) while(1) ...{ if (i >= (int)buff.shm_segsz / 7) ...{ ptr = back; i = 0; continue; } printf("从%p内存里", ptr); printf("读出字段%d : ", i); for (j = 0; j < 7; j++) ...{ printf("%c", *ptr); ptr++; } printf(" . "); usleep(5000); i++; } shmdt(&shm_id); return 0;}