shm.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /* Copyright (C) 2009 Bernhard Reutner-Fischer <uclibc@uclibc.org>
  2. *
  3. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  4. */
  5. #include <features.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <stdlib.h>
  11. #include <stdio.h>
  12. #include <errno.h>
  13. #ifndef _PATH_SHM
  14. #define _PATH_SHM "/dev/shm/"
  15. #endif
  16. #ifndef NAME_MAX
  17. #define NAME_MAX 255
  18. #endif
  19. /* Get name of dummy shm operation handle.
  20. * Returns a malloc'ed buffer containing the OS specific path
  21. * to the shm filename or NULL upon failure.
  22. */
  23. static __attribute_noinline__ char* get_shm_name(const char*name) __nonnull((1));
  24. static char* get_shm_name(const char*name)
  25. {
  26. char *path;
  27. int i;
  28. /* Skip leading slashes */
  29. while (*name == '/')
  30. ++name;
  31. #ifdef __USE_GNU
  32. i = asprintf(&path, _PATH_SHM "%s", name);
  33. if (i < 0)
  34. return NULL;
  35. #else
  36. path = malloc(NAME_MAX);
  37. if (path == NULL)
  38. return NULL;
  39. i = snprintf(path, NAME_MAX, _PATH_SHM "%s", name);
  40. if (i < 0) {
  41. free(path);
  42. return NULL;
  43. } else if (i >= NAME_MAX) {
  44. free(path);
  45. __set_errno(ENAMETOOLONG);
  46. return NULL;
  47. }
  48. #endif
  49. return path;
  50. }
  51. int shm_open(const char *name, int oflag, mode_t mode)
  52. {
  53. int fd, old_errno;
  54. char *shm_name = get_shm_name(name);
  55. /* Stripped multiple '/' from start; may have set errno properly */
  56. if (shm_name == NULL)
  57. return -1;
  58. /* The FD_CLOEXEC file descriptor flag associated with the new
  59. * file descriptor is set. */
  60. #ifdef O_CLOEXEC
  61. /* Just open it with CLOEXEC set, for brevity */
  62. fd = open(shm_name, oflag | O_CLOEXEC, mode);
  63. #else
  64. fd = open(shm_name, oflag, mode);
  65. if (fd >= 0) {
  66. int fdflags = fcntl(fd, F_GETFD, 0);
  67. if (fdflags >= 0)
  68. fdflags = fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
  69. if (fdflags < 0) {
  70. close(fd);
  71. fd = -1;
  72. }
  73. }
  74. #endif
  75. old_errno = errno;
  76. free(shm_name);
  77. errno = old_errno;
  78. return fd;
  79. }
  80. int shm_unlink(const char *name)
  81. {
  82. char *shm_name = get_shm_name(name);
  83. int ret, old_errno;
  84. /* Stripped multiple '/' from start; may have set errno properly */
  85. if (shm_name == NULL)
  86. return -1;
  87. ret = unlink(shm_name);
  88. old_errno = errno;
  89. free(shm_name);
  90. errno = old_errno;
  91. return ret;
  92. }