shared-memory/src/SharedMemory.cpp

81 lines
2.7 KiB
C++
Raw Normal View History

2019-10-23 21:39:09 +02:00
#include <cstdlib>
2019-10-19 17:12:14 +02:00
#include "SharedMemory.h"
2019-11-06 13:07:33 +01:00
#include <iostream>
2019-10-19 17:12:14 +02:00
key_t changedKey()
{
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;
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;
2019-11-06 13:07:33 +01:00
} else {
std::cout << "wrong input: pls answer with (y) for yes, (n) for no, or (override)\n";
getAnswerFromUser();
2019-11-06 13:07:33 +01:00
}
}
void initSharedMemory(void) {
if(impl.sharedMemoryKey != key_t(0)) {
if (shmget(impl.sharedMemoryKey, Max_Memory_Size, IPC_CREAT | IPC_EXCL | 0666) < 0)
{
std::cout << "Shared Memory with Key: " << 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)
{
std::cout << "Please type in a new Key:\n";
std::cout << "#";
std::cin >> impl.sharedMemoryKey;
std::cout << "new Try with Key:c " << 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 ist (Re-) allocated with Key: " << impl.sharedMemoryKey << std::endl;
}
} else {
std::cerr <<"key -> " << impl.sharedMemoryKey << " is not allowed here " << std::endl;
impl.sharedMemoryKey = changedKey();
initSharedMemory();
}
}
2019-11-06 13:07:33 +01:00
void deleteSharedMemory(int s)
{
std::cerr << "programm ended with Code: " << s << std::endl;
if (shmctl(shmget(impl.sharedMemoryKey, 0, 0), IPC_RMID, 0) < 0 )
2019-11-06 13:07:33 +01:00
{
std::cerr << "Failed to remove shared Memory, maybe not existing: try cmd: ipcs, then delete with ipcrm -m $memID " << std::endl;
2019-11-06 13:07:33 +01:00
} else {
std::cout << "shared Memory deleted" << std::endl;
}
2019-10-20 20:38:12 +02:00
}
2019-11-06 13:07:33 +01:00
void deleteSharedMemory(void)
{
if (shmctl(shmget(impl.sharedMemoryKey, 0, 0), IPC_RMID, 0) < 0 )
2019-11-06 13:07:33 +01:00
{
std::cerr << "Failed to remove shared Memory, maybe not existing: try cmd: ipcs " << std::endl;
} else {
std::cout << "shared Memory deleted" << std::endl;
2019-10-20 20:38:12 +02:00
}
}