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++ stdlib 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 stdlib? 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. Latest question on Stackoverflow about it is 15 years old, so perhaps something has been proposed to solve this in C++23 and onwards.
As of today, the C++ language by itself (including the standard library), does not support any IPC mechanism.
Moreover, the language does not even have the notion of a process (threads were added in C++11, but not processes).
Your only option is some API/library.
Some viable options:
If you can use boost (which is considered quite portable), there are 2 relevant modules:
(1) Boost.Interprocess
- contains a lot of building blocks for IPC, like synchronization objects, shared memory etc.
(2) Boost.Asio
- a library for network and low-level I/O, which has good support for sockets.
If you cannot use boost, you can use the more-or-less standard API for sockets which many common OSs support (with functions like bind
,send
, etc.).
A (personal) observation:
Of course it may vary depending on the systems requirements etc. but I found that sockets are usually a good default approach. They are relatively easy to manage, supported on most systems, have reasonable performance, and allow you to easily scale to multiple machines.