Search code examples
socketsprocesspipeipcmessage

Which kind of inter process communication (ipc) mechanism should I use at which moment?


I know that there are several methods of inter-process communication (ipc), like:

  • File
  • Signal
  • Socket
  • Message Queue
  • Pipe
  • Named pipe
  • Semaphore
  • Shared memory
  • Message passing
  • Memory-mapped file

However I was unable to find a list or a paper comparing these mechanism to each other and pointing out the benefits of them in different environemnts.

E.g I know that if I use a file which gets written by process A and process B reads it out it will work on any OS and is pretty robust, on the other hand - why shouldn't I use TCP Socket ? Has anyone a kind of overview in which cases which methods are the most suitable ?


Solution

  • Long story short:

    • Use lock files, mutexes, semaphores and barriers when processes compete for a scarce resource. They operate in a similar manner: several process try to acquire a synchronisation primitive, some of them acquire it, others are put in sleeping state until the primitive is available again. Use semaphores to limit the amount of processes working with a resource. Use a mutex to limit the amount to 1.

    • You can partially avoid using synchronisation primitives by using non-blocking thread-safe data structures.

    • Use signals, queues, pipes, events, messages, unix sockets when processes need to exchange data. Signals and events are usually used for notifying a process of something (for instance, ctrl+c in unix terminal sends a SIGINT signal to a process). Pipes, shared memory and unix sockets are for transmitting data.

    • Use sockets for networking (or, speaking formally, for exchanging data between processes located on different machines).

    Long story long: take a look at Modern Operating Systems book by Tanenbaum & Bos, namely IPC chapter. The topic is vast and can't be completely covered within a list or a paper.