Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ portable IPC

Tags:

c++

std

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++ 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.

like image 246
Dominik Kaszewski Avatar asked May 10 '26 14:05

Dominik Kaszewski


2 Answers

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:

  1. 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.

  2. 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.

like image 71
wohlstad Avatar answered May 13 '26 02:05

wohlstad


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
like image 35
Coder Avatar answered May 13 '26 04:05

Coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!