| #include <errno.h> |
| #include <stdio.h> |
| #include <stdlib.h> |
| #include <string.h> |
| #include <unistd.h> |
| #include <signal.h> |
| #include <time.h> |
| #include <pthread.h> |
| #include <sys/prctl.h> |
| #include <sys/ipc.h> |
| #include <sys/shm.h> |
| #include <sys/types.h> |
| #include <unistd.h> |
| #include <assert.h> |
| #include <sys/mman.h> |
| #include <sys/stat.h> |
| #include <fcntl.h> |
| |
| /** |
| * ºê¶¨Òå |
| */ |
| #define SHM_TEXT_SIZE (8192) |
| #define SHM_PAGE_SIZE (4096) |
| #define SHM_ALLOC_ONE_PAGE_SIZE (1024) |
| #define SHM_ALLOC_TWO_PAGE_SIZE (8100) |
| #define SHM_ALLOC_FOUR_PAGE_SIZE (16000) |
| |
| typedef struct |
| { |
| key_t key; |
| int shmid; |
| unsigned int shm_size; |
| }shm_node_t; |
| |
| typedef struct |
| { |
| int write; |
| char data[SHM_TEXT_SIZE]; |
| }shm_use_remote; |
| |
| shm_node_t shm_node; |
| |
| int main (int argc, char *argv[]) |
| { |
| int opt; |
| int ret = 0; |
| int shmid = 0; |
| unsigned int shm_size = 0; |
| key_t key = 0; |
| char *pshm = NULL; |
| char *read_data = NULL; |
| extern char *optarg; |
| |
| shm_use_remote *shared; |
| |
| while ((opt = getopt(argc,argv,"k:d:s::")) != EOF) |
| { |
| switch (opt) |
| { |
| case 'k': |
| key = atoi(optarg); |
| break; |
| case 'd': |
| read_data = optarg; |
| break; |
| case 's': |
| shm_size = atoi(optarg); |
| break; |
| default: |
| break; |
| } |
| } |
| |
| if (key == 0 || !read_data) |
| { |
| printf("param error: you can input \"shm_read -k -200 -d \"123456\" -s1024 \n"); |
| printf("or \"shm_read -k -200 -d \"123456\" \n"); |
| printf("-k -200: create a shm using key -200\n"); |
| printf("-d \"123456\": if we write 123456 to shm, then can read 123456 form shm, the test case is pass! \n"); |
| printf("-s1024: set the size of shm, then the default size is 1024 \n"); |
| return -1; |
| } |
| |
| if (shm_size == 0) |
| shm_size = SHM_ALLOC_ONE_PAGE_SIZE; |
| |
| printf("AP read test: key is %d, shm_size is %d\n", key, shm_size); |
| |
| shmid = shmget(key, shm_size, 0666|IPC_CREAT); |
| if(shmid < 0) |
| { |
| printf("shmid return error\n"); |
| return -1; |
| } |
| |
| pshm = (char *)shmat(shmid, 0, 0); |
| if (pshm == NULL) |
| { |
| printf("shmat return error\n"); |
| return -1; |
| } |
| shm_node.key = key; |
| shm_node.shm_size = shm_size; |
| |
| shared = (shm_use_remote *)pshm; |
| shared->write = 1; |
| |
| while(1) |
| { |
| if(strncmp(shared->data, read_data, sizeof(read_data)) == 0) |
| { |
| printf("Success, AP read %s from shm\n", read_data); |
| break; |
| } |
| else |
| sleep(2); |
| } |
| |
| if(shmdt(pshm) < 0) |
| { |
| printf("shmdt errno %d: %s\n", errno, strerror(errno)); |
| return -1; |
| } |
| |
| if(shmctl(shmid, IPC_RMID, NULL) == -1) |
| { |
| printf("shmctl errno %d: %s\n", errno, strerror(errno)); |
| return -1; |
| } |
| |
| printf("shm read end\n"); |
| return 0; |
| } |
| |