xref: /DragonOS/user/apps/test_shm/sender.c (revision 86ee1395de7c614865236ee15071c3603b794e44)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <sys/mman.h>
5 #include <sys/shm.h>
6 #include <sys/ipc.h>
7 #include <string.h>
8 #include <sys/wait.h>
9 
10 #define SHM_SIZE 9999
11 
12 int main()
13 {
14     int shmid;
15     char *shmaddr;
16     key_t key = 6666;
17 
18     // 测试shmget
19     shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT);
20     if (shmid < 0)
21     {
22         perror("shmget failed");
23         exit(EXIT_FAILURE);
24     }
25 
26     // 测试shmat
27     shmaddr = shmat(shmid, 0, 0);
28 
29     memset(shmaddr, 0, SHM_SIZE);
30     memcpy(shmaddr, "Sender Hello!", 14);
31 
32     int pid = fork();
33     if (pid == 0)
34     {
35         execl("/bin/test_shm_receiver", NULL, NULL);
36     }
37 
38     waitpid(pid, NULL, 0);
39 
40     char read_buf[20];
41     memcpy(read_buf, shmaddr, 16);
42     printf("Sender receive: %s\n", read_buf);
43 
44     shmdt(shmaddr);
45     shmctl(shmid, IPC_RMID, NULL);
46 }
47