tst-shm.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
  16. char shared_name[] = "/sharetest";
  17. int test_data[11] = {0,1,2,3,4,5,6,7,8,9,10};
  18. int main(void) {
  19. int pfds[2];
  20. pid_t pid;
  21. int fd;
  22. int test_data_fails = 0;
  23. char *ptest_data;
  24. unsigned int i;
  25. char buf[30];
  26. int rv;
  27. pipe(pfds);
  28. switch(pid = fork()) {
  29. case -1:
  30. perror("fork");
  31. exit(1); /* parent exits */
  32. case 0:
  33. /* Child */
  34. /* wait for parent */
  35. read(pfds[0], buf, 5);
  36. fd = shm_open(shared_name, O_RDWR, DEFFILEMODE);
  37. if (fd == -1) {
  38. perror("CHILD - shm_open(existing):");
  39. exit(1);
  40. } else {
  41. ptest_data = mmap(0, sizeof(test_data), PROT_READ + PROT_WRITE, MAP_SHARED, fd, 0);
  42. if (ptest_data != MAP_FAILED) {
  43. for (i=0; i < ARRAY_SIZE(test_data); i++) {
  44. if (ptest_data[i] != test_data[i]) {
  45. printf("%-40s: Offset %d, local %d, shm %d\n", "Compare memory error", i, test_data[i], ptest_data[i]);
  46. test_data_fails++;
  47. }
  48. }
  49. if (test_data_fails == 0)
  50. printf("%-40s: %s\n", "Compare memory", "Success");
  51. munmap(ptest_data, sizeof(test_data));
  52. }
  53. }
  54. exit(0);
  55. default:
  56. /* Parent */
  57. fd = shm_open(shared_name, O_RDWR+O_CREAT+O_EXCL, DEFFILEMODE );
  58. if (fd == -1) {
  59. perror("PARENT - shm_open(create):");
  60. } else {
  61. if ((ftruncate(fd, sizeof(test_data))) == -1)
  62. {
  63. printf("%-40s: %s", "ftruncate", strerror(errno));
  64. shm_unlink(shared_name);
  65. return 0;
  66. }
  67. ptest_data = mmap(0, sizeof(test_data), PROT_READ + PROT_WRITE, MAP_SHARED, fd, 0);
  68. if (ptest_data == MAP_FAILED)
  69. {
  70. perror("PARENT - mmap:");
  71. if (shm_unlink(shared_name) == -1) {
  72. perror("PARENT - shm_unlink:");
  73. }
  74. return 0;
  75. }
  76. for (i=0; i < ARRAY_SIZE(test_data); i++)
  77. ptest_data[i] = test_data[i];
  78. /* signal child */
  79. write(pfds[1], "rdy", 5);
  80. /* wait for child */
  81. wait(&rv);
  82. /* Cleanup */
  83. munmap(ptest_data, sizeof(test_data));
  84. if (shm_unlink(shared_name) == -1) {
  85. perror("PARENT - shm_unlink:");
  86. }
  87. }
  88. }
  89. return 0;
  90. }