app_shm_manager.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright [2021] JD.com, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. #include <errno.h>
  18. #include <string.h>
  19. #include <sys/ipc.h>
  20. #include <sys/shm.h>
  21. #include "app_shm_manager.h"
  22. char *get_shm(uint32_t key, uint32_t len, int flag, int *shm_id, bool create,
  23. int *exist)
  24. {
  25. if (!shm_id || !exist)
  26. return NULL;
  27. // printf("Key:0x%x, Len:%d, Flag:%o\n", key, len, flag);
  28. void *shm_ptr = NULL; //(void*) -1;
  29. //获取共享内存
  30. (*shm_id) = shmget(key, len, flag);
  31. if ((*shm_id) < 0) {
  32. if (ENOENT != errno) {
  33. printf("shmget failed, ShmId:%d, key:%d, len:%d, flag:%d, errno:%d, strerror:%s\n",
  34. *shm_id, key, len, flag, errno, strerror(errno));
  35. return NULL;
  36. }
  37. *exist = 0;
  38. }
  39. //不存在则创建
  40. if (!(*exist)) {
  41. if (!create) {
  42. return NULL;
  43. }
  44. (*shm_id) = shmget(key, len, flag | IPC_CREAT);
  45. if ((*shm_id) < 0) {
  46. printf("shmget failed, ShmId:%d, errno:%d, strerror:%s\n",
  47. *shm_id, errno, strerror(errno));
  48. return NULL;
  49. }
  50. }
  51. //绑定到共享内存
  52. int access_flag = 0;
  53. if ((shm_ptr = shmat((*shm_id), NULL, access_flag)) == (void *)-1) {
  54. printf("shmat failed, ShmId:%d, errno:%d, strerror:%s\n",
  55. *shm_id, errno, strerror(errno));
  56. return NULL;
  57. }
  58. return (char *)(shm_ptr);
  59. }
  60. int detach_shm(void *shmaddr)
  61. {
  62. if (!shmaddr) {
  63. return -NULL_PTR;
  64. }
  65. if (shmdt(shmaddr) == -1) {
  66. return -errno;
  67. }
  68. return 0;
  69. }