shared-memory/src/SharedMemory.cpp

86 lines
2.9 KiB
C++

#include <cstdlib>
#include "SharedMemory.h"
#include <iostream>
#include <fstream>
key_t changedKey()
{
std::ofstream keyFile;
keyFile.open("key.log", std::ofstream::out | std::ofstream::trunc);
keyFile.clear();
int newKey;
std::cout << "Type in a new Key for the Shared Memory Segment" << std::endl;
std::cout << "new Key#";
std::cin >> newKey;
std::cout <<"New Key is -> " << newKey << std::endl;
keyFile << newKey;
keyFile.close();
return key_t(newKey);
}
std::string getAnswerFromUser()
{
std::cout <<"answer# ";
std::string answer;
std::cin >> answer;
if(answer.compare("y") == 0 || answer.compare("n") == 0|| answer.compare("override") == 0) {
return answer;
} else {
std::cout << "wrong input: pls answer with (y) for yes, (n) for no, or (override)\n";
getAnswerFromUser();
}
return "-0";
}
void initSharedMemory(void) {
if(vkvm::impl.sharedMemoryKey != key_t(0)) {
if (shmget(vkvm::impl.sharedMemoryKey, Max_Memory_Size, IPC_CREAT | IPC_EXCL | 0666) < 0)
{
std::cout << "Shared Memory with Key: " << vkvm::impl.sharedMemoryKey << " is already in use\n"
<<"You can change the Key( type -> y or n ), or you can override the shared memory Segment(type -> override)\n";
std::string answer = getAnswerFromUser();
if(answer.compare("y") == 0)
{
vkvm::impl.sharedMemoryKey = changedKey();
std::cout << "new Try with Key:c " << vkvm::impl.sharedMemoryKey << std::endl;
initSharedMemory();
} else if(answer.compare("n") == 0) {
std::cout << "This will end shared memory" <<std::endl;
exit(0);
} else if(answer.compare("override") == 0) {
deleteSharedMemory();
initSharedMemory();
}
} else {
std::cout << "Shared Memory is (Re-) allocated with Key: " << vkvm::impl.sharedMemoryKey << std::endl;
}
} else {
std::cerr <<"key -> " << vkvm::impl.sharedMemoryKey << " is not allowed here " << std::endl;
vkvm::impl.sharedMemoryKey = changedKey();
initSharedMemory();
}
}
void deleteSharedMemory(int s)
{
std::cerr << "programm ended with Code: " << s << std::endl;
if (shmctl(shmget(vkvm::impl.sharedMemoryKey, 0, 0), IPC_RMID, 0) < 0 )
{
std::cerr << "Failed to remove shared Memory, maybe not existing: try cmd: ipcs, then delete with ipcrm -m $memID " << std::endl;
} else {
std::cout << "shared Memory deleted" << std::endl;
}
}
void deleteSharedMemory(void)
{
if (shmctl(shmget(vkvm::impl.sharedMemoryKey, 0, 0), IPC_RMID, 0) < 0 )
{
std::cerr << "Failed to remove shared Memory, maybe not existing: try cmd: ipcs " << std::endl;
} else {
std::cout << "shared Memory deleted" << std::endl;
}
}