Writing an OS Kernel from Scratch – Part 25: Unix Domain Sockets — The Foundation of Inter-Process Communication (IPC)

“The Display Server and Client need efficient communication, but pipes are unidirectional and unstructured. Today, we implement Unix Domain Sockets (AF_UNIX), making IPC as natural as file operations!”

In the previous post, we built the Display Server + Client architecture, but the IPC channel was a simplified pipe with clear limitations:

  • Only supports unidirectional communication
  • No connection concept → can’t distinguish multiple Clients
  • No file descriptor passing → can’t share memory handles

Real IPC needs Unix Domain Sockets:
✅ Bidirectional communication
✅ Supports SOCK_STREAM (stream) and SOCK_DGRAM (datagram)
✅ Can pass file descriptors (like shared memory, device handles)
✅ Addressed via path names (like /tmp/display.sock)

D-Bus, Wayland, and X11 are all based on Unix Domain Sockets!


Socket VFS Abstraction Layer

Sockets appear in VFS as special files, but operations go through socket system calls.

Key: The fd returned by socket() is essentially a special file!


AF_UNIX Protocol Implementation

  1. Socket structure
  2. bind: bind path name
  3. listen: listen for connections
  4. accept: accept connections
  5. connect: connect to Server

Data Transfer: send/recv

  1. Kernel message queue
  2. sendmsg (supports FD passing)
  3. recvmsg (receive FD)

The essence of FD passing: copying a file object from one process’s fd_table to another!

Last modified: 2025年2月21日

Author

Comments

Write a Reply or Comment

Your email address will not be published.