boost将当前时间写入共享内存
首先是要开辟电脑上的共享空间,利用boost的share_memory_object很容易实现
接着获取当前时间,由于获得的位UTC时间,北京时间还需要加8小时,最后写入内存。
1 #include "stdafx.h" 2 #include <boost/interprocess/shared_memory_object.hpp> 3 #include <boost/date_time/gregorian/gregorian.hpp> 4 #include <boost/date_time/posix_time/posix_time.hpp> 5 #include <boost/thread.hpp> 6 int _tmain(int argc, _TCHAR* argv[]) 7 { 8 while (true) 9 { 10 //开辟共享空间 11 boost::this_thread::sleep(boost::posix_time::minutes(3)); 12 boost::interprocess::shared_memory_object sharedMem(boost::interprocess::open_or_create,"Test",boost::interprocess::read_write); 13 sharedMem.truncate(14); 14 boost::interprocess::mapped_region mapRegion(sharedMem,boost::interprocess::read_write); 15 16 boost::posix_time::hours hourDure(8); 17 boost::posix_time::ptime pt = boost::posix_time::second_clock::universal_time(); 18 boost::posix_time::ptime ptNow = pt + hourDure; 19 20 //转换为YYYYMMDDHHMMSS格式,占14个字符 21 std::string strTime = boost::posix_time::to_iso_string(ptNow); 22 int ipos = strTime.find('T'); 23 strTime.erase(ipos,1); 24 25 memcpy(mapRegion.get_address(),strTime.c_str(),14); 26 const char* tchar = static_cast<char*>(mapRegion.get_address()); 27 std::cout<< tchar<<std::endl; 28 std::cout<< mapRegion.get_address()<<std::endl; 29 } 30 31 return 0; 32 }