blob: ccf6a838c1abb551b940bfb0197f60f85ca8d720 [file] [log] [blame]
xf.li6c8fc1e2023-08-12 00:11:09 -07001#include <errno.h>
2#include <stdio.h>
3#include <stdlib.h>
4#include <string.h>
5#include <unistd.h>
6#include <signal.h>
7#include <time.h>
8#include <pthread.h>
9#include <sys/prctl.h>
10#include <sys/ipc.h>
11#include <sys/shm.h>
12#include <sys/types.h>
13#include <unistd.h>
14#include <assert.h>
15#include <sys/mman.h>
16#include <sys/stat.h>
17#include <fcntl.h>
18
19/**
20 * ºê¶¨Òå
21 */
22#define SHM_TEXT_SIZE (8192)
23#define SHM_PAGE_SIZE (4096)
24#define SHM_ALLOC_ONE_PAGE_SIZE (1024)
25#define SHM_ALLOC_TWO_PAGE_SIZE (8100)
26#define SHM_ALLOC_FOUR_PAGE_SIZE (16000)
27
28typedef struct
29{
30 key_t key;
31 int shmid;
32 unsigned int shm_size;
33}shm_node_t;
34
35typedef struct
36{
37 int write;
38 char data[SHM_TEXT_SIZE];
39}shm_use_remote;
40
41shm_node_t shm_node;
42
43int main (int argc, char *argv[])
44{
45 int opt;
46 int ret = 0;
47 int shmid = 0;
48 unsigned int shm_size = 0;
49 key_t key = 0;
50 char *pshm = NULL;
51 char *read_data = NULL;
52 extern char *optarg;
53
54 shm_use_remote *shared;
55
56 while ((opt = getopt(argc,argv,"k:d:s::")) != EOF)
57 {
58 switch (opt)
59 {
60 case 'k':
61 key = atoi(optarg);
62 break;
63 case 'd':
64 read_data = optarg;
65 break;
66 case 's':
67 shm_size = atoi(optarg);
68 break;
69 default:
70 break;
71 }
72 }
73
74 if (key == 0 || !read_data)
75 {
76 printf("param error: you can input \"shm_read -k -200 -d \"123456\" -s1024 \n");
77 printf("or \"shm_read -k -200 -d \"123456\" \n");
78 printf("-k -200: create a shm using key -200\n");
79 printf("-d \"123456\": if we write 123456 to shm, then can read 123456 form shm, the test case is pass! \n");
80 printf("-s1024: set the size of shm, then the default size is 1024 \n");
81 return -1;
82 }
83
84 if (shm_size == 0)
85 shm_size = SHM_ALLOC_ONE_PAGE_SIZE;
86
87 printf("AP read test: key is %d, shm_size is %d\n", key, shm_size);
88
89 shmid = shmget(key, shm_size, 0666|IPC_CREAT);
90 if(shmid < 0)
91 {
92 printf("shmid return error\n");
93 return -1;
94 }
95
96 pshm = (char *)shmat(shmid, 0, 0);
97 if (pshm == NULL)
98 {
99 printf("shmat return error\n");
100 return -1;
101 }
102 shm_node.key = key;
103 shm_node.shm_size = shm_size;
104
105 shared = (shm_use_remote *)pshm;
106 shared->write = 1;
107
108 while(1)
109 {
110 if(strncmp(shared->data, read_data, sizeof(read_data)) == 0)
111 {
112 printf("Success, AP read %s from shm\n", read_data);
113 break;
114 }
115 else
116 sleep(2);
117 }
118
119 if(shmdt(pshm) < 0)
120 {
121 printf("shmdt errno %d: %s\n", errno, strerror(errno));
122 return -1;
123 }
124
125 if(shmctl(shmid, IPC_RMID, NULL) == -1)
126 {
127 printf("shmctl errno %d: %s\n", errno, strerror(errno));
128 return -1;
129 }
130
131 printf("shm read end\n");
132 return 0;
133}
134