Sobes.tech
Junior — Middle

Can you list and explain the main methods of interprocess communication in Linux?

sobes.tech AI

Answer from AI

In Linux, there are several main methods of interprocess communication (IPC) that allow processes to exchange data and synchronize:

  1. Pipes — allow data to be transferred as a byte stream from one process to another. Usually used for communication between parent and child processes.

  2. Named Pipes (FIFO) — similar to regular pipes but have a name in the filesystem, enabling data exchange between unrelated processes.

  3. Sockets — provide data exchange between processes, both on the same machine and over a network. UNIX domain sockets work locally.

  4. Shared Memory — allows processes to share a memory segment for fast data exchange.

  5. Semaphores — used for synchronizing access to shared resources between processes.

  6. Message Queues — enable processes to exchange structured messages through a queue.

Example of using a named pipe in Python:

import os
import time

fifo = '/tmp/my_fifo'

# Create FIFO if it does not exist
if not os.path.exists(fifo):
    os.mkfifo(fifo)

# Write to FIFO
with open(fifo, 'w') as fifo_out:
    fifo_out.write('Hello from process 1!')

# Read from FIFO
with open(fifo, 'r') as fifo_in:
    data = fifo_in.read()
    print(f'Received: {data}')

This code demonstrates simple message exchange via a named pipe.