sysv_shm.cpp 925 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <unistd.h>
  2. #include <sys/shm.h>
  3. #include <exception>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <tools.h>
  7. #include <sysv_shm.h>
  8. sysv_shm::sysv_shm()
  9. :_id(-1)
  10. ,_base(0)
  11. {
  12. }
  13. char*sysv_shm::ptr()
  14. {
  15. return (char*)_base;
  16. }
  17. int sysv_shm::open(const char*name,size_t size)
  18. {
  19. key_t key=hash(name,strlen(name));
  20. if((_id=shmget(key, size, IPC_CREAT|0644)) == (-1))
  21. {
  22. perror("shmget");
  23. return -1;
  24. }
  25. if((_base=shmat(_id,0,0))==(void*)(-1))
  26. {
  27. perror("shmat");
  28. return -1;
  29. }
  30. return 0;
  31. }
  32. int sysv_shm::num_attach()
  33. {
  34. struct shmid_ds sd={0};
  35. if(shmctl(_id,IPC_STAT,&sd)<0)
  36. {
  37. perror("shmctl");
  38. return -1;
  39. }
  40. return (int)sd.shm_nattch;
  41. }
  42. int sysv_shm::destroy()
  43. {
  44. if(shmctl(_id,IPC_RMID,0)<0)
  45. {
  46. perror("shmctl");
  47. return -1;
  48. }
  49. return 0;
  50. }
  51. void sysv_shm::close()
  52. {
  53. int num=num_attach();
  54. if(_base)
  55. shmdt(_base);
  56. if(num==1)
  57. destroy();
  58. }
  59. sysv_shm::~sysv_shm()
  60. {
  61. close();
  62. }