I understand that two of the many more options for inter process communication can be :
- Shared memory
- Sockets
Actually I saw these two options being exposed by Intellij Idea for debugging a Java application . I want to know what are the pros and cons of each approach .
4
A few advantages for each off the top of my head. Note that some of these items may not apply in all cases; these are just general observations.
Sockets
Simple and controlled. Can be extended to network sockets as necessary with little or no modification. Programming model requires serialization, which in turn requires you to think about what data actually gets transferred from A to B. Synchronization is necessarily built-in to the communication mechanism; no other synchronization necessary.
Shared Memory
Does not necessarily require a syscall (therefore potentially faster). Sharing does not explicitly require data to be transferred — data can be made available that the recipient does not retrieve (bandwidth does not have to be wasted transferring data that the recipient won’t use). No serialization/deserialization step means no time spent on communication overhead.
5
Sockets are one-to-one. You need multiple sockets if you want to send the same thing to multiple processes. With shared memory, you can have multiple readers, and also multiple writers.
Sockets are resource intensive. Each and every message goes through the OS. With shared memory, you map the shared memory but once into your application’s memory and from then on it’s your’s to use. However, you still need to go through the OS when you used shared memory; see below.
Sockets are synchronized (so long as you don’t use UDP). With shared memory, you almost inevitably need some additional mechanism to tell other processes that it is OK / not OK to read or write to the shared memory. Don’t do this and you will run into problems with corrupted memory. Example: Suppose process A starts reading a chunk shared memory, but gets swapped out partway through the read. Process B writes to that same chunk of shared memory. When process A restarts and continues reading shared memory, what it has read in is a mishmash of old and new data. To prevent this, you still go through the OS when you are using shared memory.
It’s fairly easy to convert a socket-based set of applications to one that uses network sockets. You can spread the processing to all the machines in your lab, or even further afield. just can’t do this with shared memory. You are locked to one machine with a shared memory-based solution.
Sockets are intended for low volumes of data, shared memory for large volumes of data. The different mechanisms exist to solve different problems.
1