Last active
December 8, 2018 23:20
-
-
Save je4d/55e3370b7c3af6a64f5e069f981d1b61 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <iomanip> | |
#include <iostream> | |
#include <sys/types.h> | |
#include <sys/shm.h> | |
#include <sys/ipc.h> | |
int main() | |
{ | |
static auto now = +[](std::ostream &os)->std::ostream& { | |
auto now = std::chrono::high_resolution_clock::now(); | |
auto now_c = std::chrono::system_clock::to_time_t(now); | |
auto us = std::chrono::duration_cast<std::chrono::microseconds>( | |
now.time_since_epoch()) | |
.count() | |
% 1000000; | |
return os << std::put_time(std::localtime(&now_c), "%F %T") << '.' | |
<< std::setw(6) << std::setfill('0') << us; | |
}; | |
std::thread t1{[] { | |
while (shmat(0, 0, SHM_RDONLY) == (char*)-1) | |
; | |
std::cout << now << " shmat(0) succeeded at " << std::endl; | |
}}; | |
std::thread t2{[] { | |
while (true) | |
{ | |
auto id = shmget(IPC_PRIVATE, 1000, 0600 | IPC_CREAT | IPC_EXCL); | |
if (id < 0) | |
{ | |
std::cout << "shmget failed" << std::endl; | |
break; | |
} | |
auto ptr = shmat(id, nullptr, 0); | |
if (ptr == (char*)-1) | |
{ | |
std::cout << "shmat(" << id << " failed" << std::endl; | |
break; | |
} | |
shmid_ds info; | |
if (shmctl(id, IPC_STAT, &info) < 0) | |
{ | |
std::cout << "shmctl IPC_STAT failed" << std::endl; | |
break; | |
} | |
if (info.shm_nattch != 1) | |
{ | |
std::cout << now << " shmget(IPC_PRIVATE) created seg with id " << id << ", size " << info.shm_segsz << " and nattach = " << info.shm_nattch << " at " << std::endl; | |
break; | |
} | |
if (shmdt(ptr) == -1) | |
{ | |
std::cout << "shmdt(" << ptr << " failed" << std::endl; | |
break; | |
} | |
if (shmctl(id, IPC_RMID, nullptr) < 0) | |
{ | |
std::cout << "shmctl IPC_RMID failed" << std::endl; | |
break; | |
} | |
} | |
}}; | |
t1.join(); | |
t2.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment