added semaphore and shared memory to print without superposition between parent and child process

This commit is contained in:
hugogogo
2022-08-22 14:52:31 +02:00
parent 5225e3258b
commit f7b31c7db7
14 changed files with 127 additions and 65 deletions

View File

@@ -310,6 +310,49 @@ void print_special(std::string str)
}
}
// https://stackoverflow.com/questions/5656530/how-to-use-shared-memory-with-linux-in-c
void* create_shared_memory(size_t size) {
// Our memory buffer will be readable and writable:
int protection = PROT_READ | PROT_WRITE;
// The buffer will be shared (meaning other processes can access it), but
// anonymous (meaning third-party processes cannot obtain an address for it),
// so only this process and its children will be able to use it:
int visibility = MAP_SHARED | MAP_ANONYMOUS;
// The remaining parameters to `mmap()` are not important for this use case,
// but the manpage for `mmap` explains their purpose.
return mmap(NULL, size, protection, visibility, -1, 0);
}
void init_semaphore()
{
int ret;
g_shmem = static_cast<sem_t*>(create_shared_memory(4));
ret = sem_init(g_shmem, 1, 1);
if (ret != 0)
{
perror("err sem_init()");
exit(EXIT_FAILURE);
}
}
void print_secure(std::string message)
{
sem_wait(g_shmem);
std::cerr << g_family << "| " << message;
sem_post(g_shmem);
}
void print_secure(int fd, std::string message)
{
sem_wait(g_shmem);
std::cerr << g_family << "| (" << std::setw(2) << fd << ") " << message;
sem_post(g_shmem);
}
// OVERLOADS
bool operator==(const listen_socket& lhs, int fd)