#pragma once #ifdef __unix__ #include #include #include #include #include template struct Shmem { std::atomic handle_; std::atomic done_counter_; }; template struct ShmemMeta { std::string shmem_name_; int shmem_fd_; Shmem* shmem_; }; template class MultiProcess { public: MultiProcess(size_t num_proc) : num_proc_(num_proc) {} ~MultiProcess(); void DebugInfo(pid_t pid); pid_t SpawnProcess(bool debug_bkpt); bool CreateShmem(); bool WriteHandleToShmem(T ipc_handle); bool WaitTillAllChildReads(); bool ReadHandleFromShmem(T& ipc_handle); bool NotifyParentDone(); private: const size_t num_proc_; bool debug_proc_; ShmemMeta shmem_meta_obj_; }; // Template Implementations template MultiProcess::~MultiProcess() { if(munmap(shmem_meta_obj_.shmem_, sizeof(Shmem)) < 0) { std::cout<<"Error Unmapping shared memory "< void MultiProcess::DebugInfo(pid_t pid) { const int delay = 1; if (pid == 0) { std::cout<<" Child Process with ID: "< pid_t MultiProcess::SpawnProcess(bool debug_bkpt) { if (num_proc_ < 0) { std::cout<<"Num Process cannot be less than 1"< bool MultiProcess::CreateShmem() { if (num_proc_ < 0) { std::cout<<"Num Process cannot be less than 1"<)) != 0) { std::cout<<"Cannot FTruncate "<*)mmap(0, sizeof(Shmem), PROT_READ | PROT_WRITE, MAP_SHARED, shmem_meta_obj_.shmem_fd_, 0); memset(&shmem_meta_obj_.shmem_->handle_, 0x00, sizeof(T)); shmem_meta_obj_.shmem_->done_counter_ = -1; return true; } template bool MultiProcess::WriteHandleToShmem(T ipc_handle) { memcpy(&shmem_meta_obj_.shmem_->handle_, &ipc_handle, sizeof(T)); shmem_meta_obj_.shmem_->done_counter_ = 0; return true; } template bool MultiProcess::WaitTillAllChildReads() { size_t write_count = 0; while (shmem_meta_obj_.shmem_->done_counter_ != num_proc_) { ++write_count; } return true; } template bool MultiProcess::ReadHandleFromShmem(T& ipc_handle) { size_t read_count = 0; while (shmem_meta_obj_.shmem_->done_counter_ == -1) { ++read_count; } memcpy(&ipc_handle, &shmem_meta_obj_.shmem_->handle_, sizeof(T)); return true; } template bool MultiProcess::NotifyParentDone() { ++shmem_meta_obj_.shmem_->done_counter_; return true; } #endif /* __unix__ */