In Linux there are multiple options for inter-process communication:

  • files
  • signals
  • sockets
  • unix domain socket, similar to an internet socket but all communications happens in the kernel. Referenced by processes as an inode, use the file system as address space
  • message queue
  • anonymous pipe: stdin, stdout, stderr
  • named pipes
  • shared memory
  • message passing
  • memory mapped files

Signals

Signals are asynchronous notifications sent to a process and were originally developed as a way for the kernel to notify a user space process about a certain event

For most of them there is a default action, but it is common to define a custom handler. Most important are:

  • SIGHUP, which tells a daemon process to re-read its config file. Default behavior: terminate process
  • SIGINT which notifies an interrupt from the user from keyboard, sent via CTRL+C. Default behavior: terminate process
  • SIGQUIT: User quit from keyboard. Default action core dump and terminate process
  • SIGKILL: Kill signal, cannot be handled via custom handlers
  • SIGSTOP: Stop process, cannot be handled
  • SIGTSTP: User caused stop from process (CTRL + Z )
  • SIGTERM: Graceful termination

Tip

trap can be used to add an hook on a signal in a bash script

#!/bin/bash
 
# Trap SIGINT (Ctrl+C) and SIGTERM to handle interruptions gracefully
trap 'echo "Signal caught! Performing cleanup..."; exit 1' SIGINT SIGTERM
 
# Trap EXIT to perform cleanup when the script ends
trap 'echo "Script finished. Cleaning up..."' EXIT
 
echo "Script is running. Press Ctrl+C to interrupt."
sleep 10  # Simulate a task that runs for 10 seconds
 
echo "Script completed successfully."
 

Named Pipes

Named pipes are pipes like stdin and stdout to which you can assign custom names. They provide FIFO delivery like traditional pipes and work with normal file IO, but they have a lifetime that is not related to the process it’s used with

Named pipes are a wrapper around pipes using the pipefs pseudo-filesystem (see Pseudo filesystems)

$ mkfifo examplepipe 
 
$ ls -l examplepipe
prw-rw-r-- 1 mh9 mh9 0 Oct  2 14:04 examplepipe 
 
$ while true ; do echo "x" > examplepipe ; sleep 5 ; done & 
[1] 19628
 
$ while true ; do cat < examplepipe ; sleep 5 ; done & 
[2] 19636
x 
x
...

Unix Domain Sockets

Domain sockets come in three flavors: stream-oriented (SOCK_STREAM), datagram-oriented (SOCK_DGRAM), and sequenced-packet (SOCK_SEQPACKET).

They provide the same API of sockets, but they are higher performance since they do not involve the network stack, and since they use the filesystem addressing, they inherit standard Unix file permission