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