Course contentsShow
← Linux
Lesson 57 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Unix Domain Sockets in Shell Scripts

Utilize Unix sockets for reliable inter-process communication between scripts and daemons.

In this lesson, you will learn how to use Unix Domain Sockets (UDS) to enable reliable, bidirectional communication between your shell scripts and background processes or daemons.

Why Sockets Instead of Pipes?

Previously, we explored named pipes (mkfifo), which are excellent for simple data flow. However, named pipes have limitations: they are strictly unidirectional and can become clogged if multiple processes try to write to them simultaneously. Unix Domain Sockets offer a more robust alternative. Think of a socket as a "two-way door" in the filesystem that allows a script and a daemon to talk back and forth without needing to worry about complex setup or network overhead.

Communicating with Netcat

In the shell, we typically interact with these sockets using nc (Netcat), which is configured to speak to a local socket file rather than a network address.

Imagine you have a background daemon (like a system logger) listening on a socket file located at /tmp/my_daemon.sock. To send a command and receive a response in your script, you would do the following:

# Send a message to the socket and capture the reply
response=$(echo "GET_STATUS" | nc -U /tmp/my_daemon.sock)

# Process the daemon's reply
echo "The daemon reported: $response"

The -U flag is the magic component here; it tells nc to treat the target path as a Unix Domain Socket rather than an IP address.

Reliable IPC

Unlike anonymous or named pipes, sockets are designed for persistent connections. If your daemon crashes or restarts, the socket file remains a reliable endpoint. Because the connection is bidirectional, your script can send a request and hold the stream open to listen for the specific acknowledgment.

While pipes are great for streaming data, sockets are the professional choice for building "client-server" relationships between your shell utilities and the background services that manage your system state. You are essentially turning your shell script into a client that can request actions from a persistent process waiting on the other side of that file-based connection.

Key Takeaway: Unix Domain Sockets provide a robust, two-way communication channel between processes using the -U flag with tools like Netcat, overcoming the limitations of standard pipe-based IPC.