example_tc_mmap.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #include "util/tc_mmap.h"
  17. #include "util/tc_option.h"
  18. #include <unistd.h>
  19. #include <iostream>
  20. #include <string.h>
  21. #include <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <fcntl.h>
  24. using namespace tars;
  25. void testCreate(size_t n)
  26. {
  27. TC_Mmap mmap;
  28. cout << "create mmap" << endl;
  29. mmap.mmap("mmap.dat", n);
  30. mmap.munmap();
  31. cout << "create mmap OK" << endl;
  32. }
  33. void testWrite(const string &s)
  34. {
  35. TC_Mmap mmap;
  36. cout << "write mmap" << endl;
  37. mmap.mmap("mmap.dat", 1000);
  38. memcpy(mmap.getPointer(), s.c_str(), s.length());
  39. sleep(10);
  40. mmap.munmap();
  41. }
  42. void testRead()
  43. {
  44. TC_Mmap mmap;
  45. cout << "read mmap" << endl;
  46. mmap.mmap("mmap.dat", 1000);
  47. string s;
  48. s.assign((char*)mmap.getPointer(), mmap.getSize());
  49. mmap.munmap();
  50. cout << s << endl;
  51. }
  52. int main(int argc, char *argv[])
  53. {
  54. try
  55. {
  56. TC_Option option;
  57. option.decode(argc, argv);
  58. int pagesize = sysconf(_SC_PAGESIZE);
  59. cout << "pagesize:" << pagesize << endl;
  60. if(option.getValue("test") == "create")
  61. {
  62. size_t n = 50;
  63. testCreate(n);
  64. }
  65. else if(option.getValue("test") == "write")
  66. {
  67. testWrite(option.getValue("c"));
  68. }
  69. else if(option.getValue("test") == "read")
  70. {
  71. testRead();
  72. }
  73. return 0;
  74. }
  75. catch(exception &ex)
  76. {
  77. cout << ex.what() << endl;
  78. }
  79. return 0;
  80. }