test_shm_receiver.c 658 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. char read_buf[20];
  23. memcpy(read_buf, shmaddr, 14);
  24. printf("Receiver receive: %s\n", read_buf);
  25. memset(shmaddr, 0, SHM_SIZE);
  26. memcpy(shmaddr, "Reveiver Hello!", 16);
  27. shmdt(shmaddr);
  28. return 0;
  29. }