C++ portable IPC

C++ portable IPC

I am porting a console application that was written in C targeting Linux. I want to make the code as portable as possible, so that it can also be used on Windows and other OSs. So far, I was able to replace all of the Linux-specific code such as pthreads, semaphores and filesystem operations with corresponding C++ STL headers.

One of the features the application has is to run as client-server architecture, to allow background calculations and persisting and reusing state when CLI client exits. I have read about various IPC method such as sockets, pipes and shared memory, but they always use unportable syscalls.

Is there any way to pull this off using just C++ and STL? The only solution I can think of is file-based communication, but it seems to hard to maintain atomicity, especially with multiple clients, and server has to poll file for changes as all notification methods seem to be OS-specific as well. Read more is 15 years old, so perhaps something has been proposed to solve this in C++23 and onwards.

Answer

No, as far as I know, nothing regarding IPC has been included in the newer C++ standards.

However, for such cases, you can use the preprocessor to write platform-specific code. This also makes your code platform-independent, as the platform-specific code is then only used on the respective system.

#ifdef _WIN32
// Windows specific code
#endif

#ifdef __linux__
// Linuxspecific code
#endif

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles