shmtest.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* Copyright (C) 2009 Mikael Lund Jepsen <mlj@iccc.dk>
  2. *
  3. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  4. */
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <sys/types.h>
  12. #include <sys/mman.h>
  13. #include <sys/stat.h>
  14. #include <sys/wait.h>
  15. char shared_name[] = "/sharetest";
  16. int test_data[11] = {0,1,2,3,4,5,6,7,8,9,10};
  17. int main(void) {
  18. int pfds[2];
  19. pid_t pid;
  20. int fd;
  21. int test_data_fails = 0;
  22. char *ptest_data;
  23. unsigned int i;
  24. char buf[30];
  25. int rv;
  26. pipe(pfds);
  27. switch(pid = fork()) {
  28. case -1:
  29. perror("fork");
  30. exit(1); /* parent exits */
  31. case 0:
  32. /* Child */
  33. /* wait for parent */
  34. read(pfds[0], buf, 5);
  35. fd = shm_open(shared_name, O_RDWR, DEFFILEMODE);
  36. if (fd == -1) {
  37. perror("CHILD - shm_open(existing):");
  38. exit(1);
  39. } else {
  40. ptest_data = mmap(0, sizeof(test_data), PROT_READ + PROT_WRITE, MAP_SHARED, fd, 0);
  41. if (ptest_data != MAP_FAILED) {
  42. for (i=0; i < sizeof(test_data); i++) {
  43. if (ptest_data[i] != test_data[i]) {
  44. printf("%-40s: Offset %d, local %d, shm %d", "Compare memory error", i, test_data[i], ptest_data[i]);
  45. test_data_fails++;
  46. }
  47. }
  48. if (test_data_fails == 0)
  49. printf("%-40s: %s\n", "Compare memory", "Success");
  50. munmap(ptest_data, sizeof(test_data));
  51. }
  52. }
  53. exit(0);
  54. default:
  55. /* Parent */
  56. fd = shm_open(shared_name, O_RDWR+O_CREAT+O_EXCL, DEFFILEMODE );
  57. if (fd == -1) {
  58. perror("PARENT - shm_open(create):");
  59. } else {
  60. if ((ftruncate(fd, sizeof(test_data))) == -1)
  61. {
  62. printf("%-40s: %s", "ftruncate", strerror(errno));
  63. shm_unlink(shared_name);
  64. return 0;
  65. }
  66. ptest_data = mmap(0, sizeof(test_data), PROT_READ + PROT_WRITE, MAP_SHARED, fd, 0);
  67. if (ptest_data == MAP_FAILED)
  68. {
  69. perror("PARENT - mmap:");
  70. if (shm_unlink(shared_name) == -1) {
  71. perror("PARENT - shm_unlink:");
  72. }
  73. return 0;
  74. }
  75. for (i=0; i <sizeof(test_data); i++)
  76. ptest_data[i] = test_data[i];
  77. /* signal child */
  78. write(pfds[1], "rdy", 5);
  79. /* wait for child */
  80. wait(&rv);
  81. /* Cleanup */
  82. munmap(ptest_data, sizeof(test_data));
  83. if (shm_unlink(shared_name) == -1) {
  84. perror("PARENT - shm_unlink:");
  85. }
  86. }
  87. }
  88. return 0;
  89. }