Test, profile & ship as a service
Prove the capstone is leak-free and race-free, then run it under systemd.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
Working code is not finished code. Run your capstone under sanitizers and valgrind until they report nothing, profile it with perf to see where time goes, and package it as a sandboxed systemd service. A clear README with build, run and test steps makes the project portfolio-ready.
Explained simply
Your shell and chat server work when you try them. Now you want proof that they also work when things go wrong, that they do not leak memory, and that they are fast enough. Then you want them to run like a real service that starts on boot.
Sanitizers are compiler options that add checks to your program. AddressSanitizer stops the program and shows the exact line when you read past the end of an array or use memory after free. Valgrind finds similar bugs without recompiling, but runs much slower.
A profiler tells you where the time really goes. Programmers are often wrong when they guess. perf samples the program thousands of times a second and shows which functions were running most often.
Finally, systemd starts the server at boot, restarts it if it crashes, collects its logs, and can lock it into a tight sandbox. A short README tells others how to build, run and test it. Together these turn a homework project into something you can show an employer.
Press Play on a diagram to walk through it one step at a time.
- 1Build strictly
-Wall -Wextra -Werror, plus ASan and TSan builds.
- 2Test
Scripted clients, edge cases, abrupt disconnects.
- 3Check memory
valgrind --leak-check=full reports zero leaks.
- 4Profile
perf record -g and perf report on the hot path.
- 5Ship
Install the binary and unit file, enable the service.
- 1Reproduce
Write a test or script that triggers the bug.
- 2Run under ASan or TSan
Get the exact line and stack trace.
- 3Fix the cause
Not just the symptom.
- 4Keep the test
It becomes a regression test.
- 5Run the full suite
Every build: debug, sanitizers, valgrind.
- Back to step 1
- 1Unit tests
Tokenizer, parser, line splitter, buffer code.
- 2Integration tests
Real processes and sockets with scripted input.
- 3Fault tests
Huge lines, abrupt disconnects, full buffers, signals.
- 4Load tests
Hundreds of clients; watch CPU, memory and fd counts.
- 5Checker runs
The whole suite under ASan, UBSan, TSan and valgrind.
In depth
Sanitizers and valgrind: what each one catches
Build with -g -O1 -fno-omit-frame-pointer -fsanitize=address,undefined for daily testing. AddressSanitizer (ASan) finds buffer overflows, use-after-free and double free, and on Linux it also reports leaks at exit (LeakSanitizer). The slowdown is about 2x. UndefinedBehaviorSanitizer (UBSan) finds signed overflow, bad shifts and misaligned access; add -fno-sanitize-recover=all so the first problem stops the program and fails the test.
ThreadSanitizer (-fsanitize=thread) finds data races, which matters for the thread-pool version of the server. It cannot be combined with ASan, so it needs its own build. A single-threaded epoll server has no data races to find.
Valgrind's memcheck needs no rebuild but runs roughly 10 to 50 times slower. Never run a sanitizer build under valgrind. For leak reports to mean anything, the server must shut down cleanly; memory still held at exit shows up as still reachable.
- Recompile with -fsanitize
- About 2x slower
- Overflows, use-after-free, leaks, UB
- Use on every test run
- Separate build, not with ASan
- Often 5 to 15x slower
- Data races between threads
- Only useful with threads
- No rebuild needed
- Roughly 10 to 50x slower
- Leaks, invalid reads, uninitialised values
- Good final check of the release binary
Profiling with perf
Profile a build that is close to release: -O2 -g -fno-omit-frame-pointer. Optimisation changes where time goes, so profiling a -O0 build misleads you. The frame pointer lets perf record -g rebuild call stacks cheaply; without it, use perf record --call-graph dwarf, which is accurate but produces much bigger files.
Start the server, generate realistic load with your test clients, then attach with perf record -g -p PID for 20 to 30 seconds and open the result with perf report. Look at the functions with the highest self time first. For a chat server it is usually broadcast work: copying the same line into many buffers, memmove on large buffers, or one send call per client.
perf stat ./prog gives quick totals such as task-clock, context switches and page faults. If perf refuses to run as a normal user, check /proc/sys/kernel/perf_event_paranoid. Always measure again after a change, and keep the change only if the number really improved.
- 1Build -O2 -g
Add -fno-omit-frame-pointer for good stacks.
- 2Apply real load
Hundreds of scripted clients sending lines.
- 3perf record -g -p PID
Sample for about 30 seconds.
- 4perf report
Sort by self time, find the hottest function.
- 5Change one thing
Then measure again and compare.
A hardened systemd unit
Put the unit in /etc/systemd/system/chatd.service. The [Service] section needs ExecStart with the full path to the binary. Restart=on-failure brings the server back after a crash, and RestartSec=2 stops a broken binary from restarting in a tight loop. Let the program log to stdout and stderr; systemd sends that to the journal, which you read with journalctl -u chatd -f.
DynamicUser=yes runs the service as a temporary unprivileged user created at start, and it switches on several protections such as a read-only view of the system. Add NoNewPrivileges=yes, PrivateTmp=yes, ProtectSystem=strict and ProtectHome=yes. Run systemd-analyze security chatd to get an exposure score and a list of settings still open.
On stop, systemd sends SIGTERM, then SIGKILL after TimeoutStopSec (90 seconds by default). Your signalfd shutdown code is what makes the stop clean. After editing a unit, run systemctl daemon-reload.
- Ports below 1024 need AmbientCapabilities=CAP_NET_BIND_SERVICE
- LimitNOFILE=65536 raises the fd limit for many clients
- systemd-analyze verify chatd.service checks the file for errors
- [Unit]
- Description=
- After=network.target
- [Service] running
- ExecStart=/usr/local/bin/chatd 7000
- Restart=on-failure
- RestartSec=2
- [Service] sandbox
- DynamicUser=yes
- NoNewPrivileges=yes
- ProtectSystem=strict
- ProtectHome=yes
- PrivateTmp=yes
- [Install]
- WantedBy=multi-user.target
Tests that try to break it, and a useful README
Happy-path tests prove little. Write a script that starts the server, runs scripted clients, compares their output with what you expect, and exits non-zero on any difference. Then add hostile cases: a 1 MB line, a client that disconnects mid-line, a client that never reads, 1,000 clients connecting at once, and a SIGTERM while clients are sending. For the shell, feed scripted input through a pipe and test empty lines, missing files after > and long pipelines.
Every bug you fix gets a regression test, so it cannot quietly return. Run the whole suite on the sanitizer build and on the valgrind run with --error-exitcode=1, so a single leak or invalid read fails the run.
The README should answer, in order: what it is, how to build it (compiler and make targets), how to run it, the protocol or supported syntax, how to run the tests, design decisions with their trade-offs, and known limits. Reviewers read this before any code.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Run valgrind and sanitizers clean~45m
- 2Profile hot paths with perf~45m
- 3Write a systemd unit for the server~45m
- 4Document build and usage in a README~45m
Key points
- Keep separate debug, sanitizer and release targets in the Makefile.
- ASan and TSan cannot be combined in one build, so run them separately.
- perf top and perf record -g show which functions burn CPU.
- Test failure paths: kill clients, fill buffers and send huge lines.
Key terms
Tap a card to flip it. 0/5 known
Examples
make CFLAGS="-g -O1 -fsanitize=address,undefined" && ./run-tests.sh
make clean && make CFLAGS="-g -O1 -fsanitize=thread" && ./run-tests.sh
valgrind --leak-check=full --error-exitcode=1 ./chatd 7000
perf record -g ./chatd 7000 # generate load, then Ctrl-C
perf report
sudo install -m 755 chatd /usr/local/bin/ && sudo systemctl enable --now chatdSanitizers, valgrind, profiling, then install as a service.
A Makefile with debug, sanitizer and release builds
One Makefile builds three kinds of binary. make asan is what you run every day: it catches memory errors and undefined behaviour and stops at the first one. make tsan is for the threaded version only. make release is what you profile and install. Each target cleans first, because objects from different flag sets must not be mixed. Recipe lines in a Makefile must start with a tab.
CC ?= cc
WARN := -Wall -Wextra -Werror -std=c11 -D_GNU_SOURCE
SRC := chatd.c net.c proto.c
chatd: $(SRC)
$(CC) $(WARN) $(CFLAGS) -o $@ $(SRC) $(LDFLAGS)
asan: ; $(MAKE) clean && $(MAKE) CFLAGS="-g -O1 -fno-omit-frame-pointer -fsanitize=address,undefined -fno-sanitize-recover=all"
tsan: ; $(MAKE) clean && $(MAKE) CFLAGS="-g -O1 -fsanitize=thread"
release: ; $(MAKE) clean && $(MAKE) CFLAGS="-O2 -g -fno-omit-frame-pointer"
test: asan ; ./tests/run.sh ./chatd
clean: ; rm -f chatd
.PHONY: asan tsan release test cleanInstalling chatd as a sandboxed service
Copy the release binary to /usr/local/bin, write the unit file below to /etc/systemd/system/chatd.service, then run systemctl daemon-reload and systemctl enable --now chatd. Check it with systemctl status chatd and follow the logs with journalctl -u chatd -f. Kill it with sudo kill -SEGV on its PID to see Restart=on-failure bring it back after 2 seconds. Finally run systemd-analyze security chatd and see how the sandbox settings lowered the exposure score.
[Unit]
Description=Invicly chat server
After=network.target
[Service]
ExecStart=/usr/local/bin/chatd 7000
Restart=on-failure
RestartSec=2
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
LimitNOFILE=65536
[Install]
WantedBy=multi-user.targetQuick reference
- Daily build: -g -O1 -fno-omit-frame-pointer -fsanitize=address,undefined -fno-sanitize-recover=all
- ASan and TSan cannot share one binary; never run a sanitizer build under valgrind.
- valgrind --leak-check=full --error-exitcode=1 ./chatd 7000 fails the run on any error.
- perf record -g -p PID, then perf report; use --call-graph dwarf if stacks look broken.
- perf stat ./prog shows task-clock, context switches and page faults in one run.
- systemctl daemon-reload after editing a unit; journalctl -u chatd -f to follow logs.
- systemd-analyze security chatd scores the sandbox; systemd-analyze verify checks syntax.
- systemd stops a service with SIGTERM, then SIGKILL after TimeoutStopSec (default 90 s).
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Build your server with ASan and UBSan, run it, and add a deliberate bug (write one byte past the end of the input buffer) to see what the report looks like. Then remove the bug.
- Exercise 2medium
Write and install a systemd unit for chatd, then lower its systemd-analyze security exposure score by adding at least four sandbox settings, checking that the server still works after each one.
- Exercise 3hard
Write tests/run.sh that starts the server on a free port, runs two scripted clients, checks that a message from one reaches the other exactly once, always stops the server, and exits non-zero on failure. Make it work under valgrind too.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between definitely lost and still reachable in valgrind?
- Definitely lost means no pointer to the block exists anymore, which is a real leak to fix. Still reachable means a pointer still existed at exit, which often just means the program did not free everything before quitting.
- Should I use ASan or valgrind?
- Use ASan for everyday testing because it is much faster and gives precise reports. Use valgrind as an extra check on the release binary, since it needs no rebuild and also finds reads of uninitialised memory.
- Where do my program's printf logs go when it runs under systemd?
- By default stdout and stderr go to the journal. Read them with journalctl -u chatd, and remember to fflush or use line buffering, because stdout is fully buffered when it is not a terminal.
- How do I make a flame graph from perf data?
- Record with perf record -g, then use Brendan Gregg's FlameGraph scripts: perf script | stackcollapse-perf.pl | flamegraph.pl > out.svg. Open the SVG in a browser and look for the widest bars.