sender.c 852 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. #define SHM_SIZE 9999
  10. int main()
  11. {
  12. int shmid;
  13. char *shmaddr;
  14. key_t key = 6666;
  15. // 测试shmget
  16. shmid = shmget(key, SHM_SIZE, 0666 | IPC_CREAT);
  17. if (shmid < 0)
  18. {
  19. perror("shmget failed");
  20. exit(EXIT_FAILURE);
  21. }
  22. // 测试shmat
  23. shmaddr = shmat(shmid, 0, 0);
  24. memset(shmaddr, 0, SHM_SIZE);
  25. memcpy(shmaddr, "Sender Hello!", 14);
  26. int pid = fork();
  27. if (pid == 0)
  28. {
  29. execl("/bin/test_shm_receiver", NULL, NULL);
  30. }
  31. waitpid(pid, NULL, 0);
  32. char read_buf[20];
  33. memcpy(read_buf, shmaddr, 16);
  34. printf("Sender receive: %s\n", read_buf);
  35. shmdt(shmaddr);
  36. shmctl(shmid, IPC_RMID, NULL);
  37. }