test_shm_sender.c 792 B

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