LINUX TCP SOCKET SERVER
Published:
Tutorial on building a custom TCP/IP Socket Server using C and POSIX
Introduction
I wanted to build a small TCP service that behaves like a proper Linux daemon, not just a toy socket program. The goal was to understand how network services interact with the operating system at runtime: connection handling, signal delivery, file I/O, logging, and clean shutdown. The result is a socket server written in C that listens on port 9000, accepts client connections, appends newline-delimited data to a file, and returns the accumulated contents back to the client, all while supporting daemon mode, syslog logging, and graceful termination.
Requirements
- Transport: TCP stream socket bound to port 9000 with a configurable connection backlog.
- Connection handling: Continuously accept incoming connections; each client is handled in a forked child process.
- Logging: Record lifecycle events using syslog, including accepted connections, closed connections, and shutdown events.
- Data protocol: Treat a newline character (
\n) as a packet delimiter for client input. - Persistence: Append received packets to
/var/tmp/aesdsocketdata, creating the file if it does not exist. - Response behavior: After appending a packet, send the entire contents of the data file back to the client.
- Concurrency safety: Use file locking to prevent corruption during concurrent reads and writes.
- Graceful shutdown: Handle
SIGINTandSIGTERMby completing active connections, closing sockets, deleting temporary data, and exiting cleanly. - Daemon support: When started with
-d, run as a background daemon with PID file creation and detached standard I/O.