: nply/liveside

commit cd82406424782feb8dcc615b7b767822b5070e0e
parent 24d421b859b5d178391bd23c5d2e241e82c206fa
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Tue, 25 Aug 2026 09:02:46 +0530

Add support for msvc
3 files changed, 386 insertions(+), 115 deletions(-)
M
Makefile
|
15
++++++++++++---
M
README.md
|
50
++++++++++++++++++++++++++++++++++++++++++--------
M
liveside.c
|
436
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
diff --git a/Makefile b/Makefile
@@ -1,8 +1,17 @@
 CC      ?= gcc
 CFLAGS  += -Wall -Wextra -O2 -std=c99 -pedantic
-LDLIBS  += -lpthread
 
-BIN = liveside
+# For a native MSVC build, don't use this Makefile at all -- see README.md
+# for the plain `cl` command line instead. This is for gcc/clang, whether
+# that's macOS/Linux/BSD directly, or a MinGW-w64/MSYS2 gcc on Windows
+# ($(OS) is set to Windows_NT by cmd.exe and by MinGW/MSYS shells).
+ifeq ($(OS),Windows_NT)
+	BIN = liveside.exe
+	LDLIBS += -lws2_32
+else
+	BIN = liveside
+	LDLIBS += -lpthread
+endif
 
 all: $(BIN)
 

@@ -10,6 +19,6 @@ $(BIN): liveside.c
 	$(CC) $(CFLAGS) -o $@ liveside.c $(LDLIBS)
 
 clean:
-	-@rm -f $(BIN)
+	-@rm -f liveside liveside.exe
 
 .PHONY: all clean
diff --git a/README.md b/README.md
@@ -1,9 +1,16 @@
 # liveside
 
-A tiny live-reload server written in plain C (no external dependencies,
-just POSIX + pthreads). It watches a directory tree for changes and
-pushes the browser a Server-Sent Events (SSE) `reload` message, which
-reloads the page.
+A tiny live-reload server written in portable C99 — no external
+dependencies, and no assumption of POSIX. It watches a directory tree
+for changes and pushes the browser a Server-Sent Events (SSE) `reload`
+message, which reloads the page.
+
+Runs on macOS, Linux, the BSDs, and Windows (MSVC, or gcc via MinGW-w64/
+MSYS2). All the platform-specific bits — sockets, threads, sleeping,
+monotonic time, directory listing, `getopt` — sit behind one small
+abstraction near the top of [liveside.c](liveside.c) with a POSIX
+implementation and a Windows one; the rest of the file never touches
+`pthread`/BSD sockets/POSIX calls directly.
 
 It is deliberately **not** a static file server — it only ever answers
 two requests, `/livereload` (the SSE stream) and `/liveside.js` (the

@@ -18,12 +25,36 @@ without AppleScript/xdotool or driving a specific app.
 
 ## Build
 
-No dependencies beyond a C99 compiler and pthreads:
+**macOS / Linux / BSD**, or **Windows via MinGW-w64/MSYS2 gcc**:
 
 ```bash
 make
 ```
 
+The Makefile detects Windows (`$(OS)=Windows_NT`, set by cmd.exe and by
+MinGW/MSYS shells) and links `-lws2_32` instead of `-lpthread`, producing
+`liveside.exe`.
+
+**Windows via MSVC** doesn't use this Makefile (its `nmake` syntax is a
+different enough beast that trying to share one Makefile isn't worth
+it) — compile directly:
+
+```
+cl /std:c11 /O2 liveside.c ws2_32.lib
+```
+
+`/std:c11` is needed for the designated initializers used in a couple of
+struct literals (`struct sockaddr_in addr = { 0 };` etc.) — available
+since VS2019 16.8. Also assumes a Universal CRT (VS2015+) for `snprintf`.
+Older MSVC versions may need those two spots adjusted by hand.
+
+Caveat: **the Windows path is implemented against documented Win32/
+Winsock2 APIs but not build-verified from this session** (no Windows
+machine or working cross-compiler toolchain was available to test
+against) — only the POSIX path has actually been compiled and run. If
+something doesn't compile under your specific MSVC version, it's most
+likely one of the two spots above.
+
 ## Run
 
 ```bash

@@ -71,9 +102,12 @@ knows where to find the SSE stream.
 - **Linux**: same idea via `inotify`, but watches are per-directory
   (inotify reports changes to files *inside* a watched directory, unlike
   kqueue), so it needs far fewer watch descriptors for the same tree.
-- **Everywhere else**: falls back to polling — recursively hashing each
-  file's name, size, and mtime every `poll-ms` and comparing to the
-  previous hash.
+- **Everywhere else, including Windows**: falls back to polling —
+  recursively hashing each file's name, size, and mtime every `poll-ms`
+  and comparing to the previous hash. Windows has its own native
+  equivalent (`ReadDirectoryChangesW`) but this doesn't use it yet;
+  polling works fine, just with up to `poll-ms` of latency instead of
+  being instant.
 
 Directories named `.git`, `node_modules`, `dist`, `.cache`, or starting
 with `.` are never watched.
diff --git a/liveside.c b/liveside.c
@@ -12,27 +12,235 @@
  *
  * File-change detection is platform-native where available (kqueue on
  * macOS/BSD, inotify on Linux) so reloads are instant instead of waiting
- * on a poll interval; anywhere else it falls back to polling.
+ * on a poll interval; anywhere else (including Windows) it falls back to
+ * polling.
+ *
+ * Portability layer: everything platform-specific (sockets, threads,
+ * mutexes, sleep, monotonic time, directory listing, getopt) is behind a
+ * small abstraction defined right below, with a POSIX implementation and
+ * a Windows one. The rest of the file only ever calls the abstraction
+ * (sock_t, thread_t/thread_spawn/thread_detach, mutex_t/mutex_lock, etc.),
+ * never raw pthread/BSD-socket/POSIX calls directly.
  */
 
-#include <dirent.h>
 #include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <pthread.h>
 #include <signal.h>
 #include <stdbool.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <time.h>
+
+#ifdef _WIN32
+
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <sys/stat.h>
+#pragma comment(lib, "ws2_32.lib")
+
+typedef SOCKET sock_t;
+#define SOCK_INVALID INVALID_SOCKET
+#define CLOSESOCK closesocket
+/* Winsock2's WSAPOLLFD is source-compatible with POSIX struct pollfd
+ * (Microsoft tagged it `pollfd` on purpose), so this just works. */
+#define poll(fds, n, to) WSAPoll((fds), (n), (to))
+
+#ifndef S_ISDIR
+#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
+#endif
+#ifndef S_ISREG
+#define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
+#endif
+#define lstat stat
+
+/* MSVC's CRT has no dirent.h. This shim, backed by FindFirstFile/
+ * FindNextFile, only needs to support what the WATCH_POLL backend below
+ * actually does with it (the only watcher backend that compiles on
+ * Windows, since kqueue/inotify are macOS/Linux-only) -- open a
+ * directory, list entries by name, close it. */
+struct dirent {
+	char d_name[MAX_PATH];
+};
+
+typedef struct {
+	HANDLE h;
+	WIN32_FIND_DATAA fd;
+	int first;
+	struct dirent ent;
+} DIR;
+
+static DIR *opendir(const char *path)
+{
+	char pattern[MAX_PATH];
+	snprintf(pattern, sizeof(pattern), "%s\\*", path);
+
+	DIR *d = (DIR *)calloc(1, sizeof(*d));
+	if (!d)
+		return NULL;
+
+	d->h = FindFirstFileA(pattern, &d->fd);
+	if (d->h == INVALID_HANDLE_VALUE) {
+		free(d);
+		return NULL;
+	}
+	d->first = 1;
+	return d;
+}
+
+static struct dirent *readdir(DIR *d)
+{
+	if (!d->first && !FindNextFileA(d->h, &d->fd))
+		return NULL;
+	d->first = 0;
+	snprintf(d->ent.d_name, sizeof(d->ent.d_name), "%s", d->fd.cFileName);
+	return &d->ent;
+}
+
+static void closedir(DIR *d)
+{
+	if (!d)
+		return;
+	FindClose(d->h);
+	free(d);
+}
+
+/* getopt() isn't in MSVC's CRT either. This is intentionally minimal --
+ * one option per argv element, no combined short options ("-abc"), no
+ * "--" terminator -- because that's the only way liveside's own -p/-d/
+ * -c/-i/-h options are ever documented or invoked. */
+static char *optarg;
+static int optind = 1;
+
+static int getopt(int argc, char *const argv[], const char *optstring)
+{
+	if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
+		return -1;
+
+	char opt = argv[optind][1];
+	const char *p = strchr(optstring, opt);
+	if (!p) {
+		optind++;
+		return '?';
+	}
+
+	optind++;
+	if (p[1] == ':') {
+		if (optind >= argc)
+			return '?';
+		optarg = argv[optind++];
+	}
+	return opt;
+}
+
+typedef HANDLE thread_t;
+typedef CRITICAL_SECTION mutex_t;
+
+static void mutex_init(mutex_t *m) { InitializeCriticalSection(m); }
+static void mutex_lock(mutex_t *m) { EnterCriticalSection(m); }
+static void mutex_unlock(mutex_t *m) { LeaveCriticalSection(m); }
+
+struct thread_start_ctx {
+	void *(*fn)(void *);
+	void *arg;
+};
+
+static DWORD WINAPI thread_trampoline(LPVOID p)
+{
+	struct thread_start_ctx *ctx = (struct thread_start_ctx *)p;
+	void *(*fn)(void *) = ctx->fn;
+	void *arg = ctx->arg;
+	free(ctx);
+	fn(arg);
+	return 0;
+}
+
+static int thread_spawn(thread_t *t, void *(*fn)(void *), void *arg)
+{
+	struct thread_start_ctx *ctx =
+		(struct thread_start_ctx *)malloc(sizeof(*ctx));
+	if (!ctx)
+		return -1;
+	ctx->fn = fn;
+	ctx->arg = arg;
+	*t = CreateThread(NULL, 0, thread_trampoline, ctx, 0, NULL);
+	return *t ? 0 : -1;
+}
+
+static void thread_detach(thread_t t) { CloseHandle(t); }
+
+static void msleep(long ms) { Sleep((DWORD)ms); }
+
+static long long now_ms(void) { return (long long)GetTickCount64(); }
+
+static long io_send(sock_t fd, const void *buf, size_t len)
+{
+	return send(fd, (const char *)buf, (int)len, 0);
+}
+
+static long io_recv(sock_t fd, void *buf, size_t len)
+{
+	return recv(fd, (char *)buf, (int)len, 0);
+}
+
+#define socket_perror(msg) \
+	fprintf(stderr, "%s: WSA error %d\n", (msg), WSAGetLastError())
+
+#else /* POSIX */
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
 #include <sys/socket.h>
 #include <sys/stat.h>
-#include <time.h>
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <unistd.h>
 
+typedef int sock_t;
+#define SOCK_INVALID (-1)
+#define CLOSESOCK close
+
+typedef pthread_t thread_t;
+typedef pthread_mutex_t mutex_t;
+
+static void mutex_init(mutex_t *m) { pthread_mutex_init(m, NULL); }
+static void mutex_lock(mutex_t *m) { pthread_mutex_lock(m); }
+static void mutex_unlock(mutex_t *m) { pthread_mutex_unlock(m); }
+
+static int thread_spawn(thread_t *t, void *(*fn)(void *), void *arg)
+{
+	return pthread_create(t, NULL, fn, arg);
+}
+
+static void thread_detach(thread_t t) { pthread_detach(t); }
+
+static void msleep(long ms) { usleep((useconds_t)ms * 1000); }
+
+static long long now_ms(void)
+{
+	struct timespec ts;
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+static long io_send(sock_t fd, const void *buf, size_t len)
+{
+	return (long)send(fd, buf, len, 0);
+}
+
+static long io_recv(sock_t fd, void *buf, size_t len)
+{
+	return (long)recv(fd, buf, len, 0);
+}
+
+#define socket_perror perror
+
+#endif /* _WIN32 */
+
 #if defined(__APPLE__)
 	#define WATCH_KQUEUE 1
 	#include <sys/event.h>

@@ -40,7 +248,6 @@
 	#include <sys/time.h>
 #elif defined(__linux__)
 	#define WATCH_INOTIFY 1
-	#include <poll.h>
 	#include <sys/inotify.h>
 #else
 	#define WATCH_POLL 1

@@ -94,10 +301,18 @@ static void kq_add_path(watcher_t *w, const char *path)
 	if (fd < 0)
 		return;
 
+	/* Deliberately no NOTE_ATTRIB: it fires on *any* attribute change,
+	 * not just content-relevant ones, including a plain atime bump from
+	 * something merely reading the file (e.g. Spotlight/mdworker
+	 * indexing it shortly after a save) -- indistinguishable from a real
+	 * edit but with nothing to actually reload. NOTE_WRITE/NOTE_EXTEND
+	 * already cover real content changes; a bare `touch` with no
+	 * write() won't trigger a reload here, which is the right call for
+	 * this tool's purpose. */
 	struct kevent kev;
 	EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR,
 		NOTE_WRITE | NOTE_DELETE | NOTE_RENAME | NOTE_EXTEND |
-		NOTE_ATTRIB | NOTE_LINK,
+		NOTE_LINK,
 		0, NULL);
 	if (kevent(w->kq, &kev, 1, NULL, 0, NULL) < 0) {
 		close(fd);

@@ -184,7 +399,7 @@ static bool watch_wait(watcher_t *w)
 	 * build) is what refreshes the watch set. Rebuilding here too would
 	 * just double the (expensive, one-open()-per-file) cost of every
 	 * detected change for no benefit. */
-	usleep(80 * 1000);
+	msleep(80);
 	struct kevent drain[64];
 	struct timespec zero = {0, 0};
 	while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0)

@@ -198,7 +413,7 @@ static bool watch_wait(watcher_t *w)
  * on watch_settle's call site in watcher_loop for why this exists. */
 static void watch_settle(watcher_t *w)
 {
-	usleep(150 * 1000);
+	msleep(150);
 	struct kevent drain[64];
 	struct timespec zero = {0, 0};
 	while (kevent(w->kq, NULL, 0, drain, 64, &zero) > 0)

@@ -234,10 +449,19 @@ static void in_add_dir(watcher_t *w, const char *path)
 {
 	/* inotify watches report changes to files *inside* a watched
 	 * directory, so unlike kqueue we only need one watch per directory,
-	 * not per file. */
+	 * not per file.
+	 *
+	 * Deliberately no IN_ATTRIB, matching kq_add_path's reasoning on the
+	 * kqueue side: it fires on any metadata change including a plain
+	 * atime bump from something merely reading the file (e.g. a search
+	 * indexer), which was confirmed (on macOS/kqueue; untested here on
+	 * Linux, but the same class of issue applies) to cause a spurious
+	 * second "change" shortly after a real edit, with nothing new to
+	 * actually reload. IN_MODIFY/IN_CLOSE_WRITE already cover real
+	 * content changes. */
 	int wd = inotify_add_watch(w->fd, path,
 		IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM |
-		IN_MOVED_TO | IN_ATTRIB | IN_CLOSE_WRITE);
+		IN_MOVED_TO | IN_CLOSE_WRITE);
 	if (wd < 0)
 		return;
 

@@ -298,7 +522,7 @@ static bool watch_wait(watcher_t *w)
 	if (n == 0)
 		return true;
 
-	usleep(80 * 1000);
+	msleep(80);
 	struct pollfd pfd = {.fd = w->fd, .events = POLLIN};
 	while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN))
 		read(w->fd, buf, sizeof(buf));

@@ -314,7 +538,7 @@ static bool watch_wait(watcher_t *w)
  * on watch_settle's call site in watcher_loop for why this exists. */
 static void watch_settle(watcher_t *w)
 {
-	usleep(150 * 1000);
+	msleep(150);
 	char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
 	struct pollfd pfd = {.fd = w->fd, .events = POLLIN};
 	while (poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN))

@@ -333,7 +557,7 @@ static void watch_close(watcher_t *w)
 	free(w);
 }
 
-#else /* WATCH_POLL */
+#else /* WATCH_POLL -- also what Windows builds use */
 
 struct watcher {
 	char root[4096];

@@ -391,7 +615,7 @@ static watcher_t *watch_open(const char *root)
 static bool watch_wait(watcher_t *w)
 {
 	while (g_running) {
-		usleep((useconds_t)g_poll_ms * 1000);
+		msleep(g_poll_ms);
 		unsigned long cur = poll_snapshot(w->root);
 		if (cur != w->last) {
 			w->last = cur;

@@ -422,48 +646,48 @@ static void watch_close(watcher_t *w)
 
 #define MAX_CLIENTS 64
 
-static int g_client_fds[MAX_CLIENTS];
+static sock_t g_client_fds[MAX_CLIENTS];
 static int g_nclients = 0;
-static pthread_mutex_t g_clients_mu = PTHREAD_MUTEX_INITIALIZER;
+static mutex_t g_clients_mu;
 
-static void add_client(int fd)
+static void add_client(sock_t fd)
 {
-	pthread_mutex_lock(&g_clients_mu);
+	mutex_lock(&g_clients_mu);
 	if (g_nclients < MAX_CLIENTS) {
 		g_client_fds[g_nclients++] = fd;
 	} else {
 		fprintf(stderr, "[liveside] client limit reached, dropping\n");
-		close(fd);
+		CLOSESOCK(fd);
 	}
-	pthread_mutex_unlock(&g_clients_mu);
+	mutex_unlock(&g_clients_mu);
 }
 
-static void remove_client(int fd)
+static void remove_client(sock_t fd)
 {
-	pthread_mutex_lock(&g_clients_mu);
+	mutex_lock(&g_clients_mu);
 	for (int i = 0; i < g_nclients; i++) {
 		if (g_client_fds[i] == fd) {
 			g_client_fds[i] = g_client_fds[--g_nclients];
 			break;
 		}
 	}
-	close(fd);
-	pthread_mutex_unlock(&g_clients_mu);
+	CLOSESOCK(fd);
+	mutex_unlock(&g_clients_mu);
 }
 
 /* Sends `msg` to every connected SSE client, dropping any that fail. */
 static void broadcast(const char *msg, size_t len)
 {
-	int dead[MAX_CLIENTS];
+	sock_t dead[MAX_CLIENTS];
 	int ndead = 0;
 
-	pthread_mutex_lock(&g_clients_mu);
+	mutex_lock(&g_clients_mu);
 	int n = g_nclients;
 	for (int i = 0; i < n; i++) {
-		if (write(g_client_fds[i], msg, len) < 0)
+		if (io_send(g_client_fds[i], msg, len) < 0)
 			dead[ndead++] = g_client_fds[i];
 	}
-	pthread_mutex_unlock(&g_clients_mu);
+	mutex_unlock(&g_clients_mu);
 
 	for (int i = 0; i < ndead; i++)
 		remove_client(dead[i]);

@@ -481,7 +705,7 @@ static void *ping_thread(void *arg)
 	(void)arg;
 	static const char ping[] = ": keep-alive\n\n";
 	while (g_running) {
-		sleep(30);
+		msleep(30000);
 		if (g_nclients > 0)
 			broadcast(ping, sizeof(ping) - 1);
 	}

@@ -520,7 +744,7 @@ static const char CLIENT_JS[] =
 "	connect();\n"
 "})();\n";
 
-static void handle_livereload(int fd)
+static void handle_livereload(sock_t fd)
 {
 	static const char headers[] =
 		"HTTP/1.1 200 OK\r\n"

@@ -531,8 +755,8 @@ static void handle_livereload(int fd)
 		"\r\n"
 		": connected\n\n";
 
-	if (write(fd, headers, sizeof(headers) - 1) < 0) {
-		close(fd);
+	if (io_send(fd, headers, sizeof(headers) - 1) < 0) {
+		CLOSESOCK(fd);
 		return;
 	}
 

@@ -543,14 +767,14 @@ static void handle_livereload(int fd)
 	 * goes away; broadcast()/ping_thread() do all the writing. */
 	char buf[64];
 	while (g_running) {
-		ssize_t n = read(fd, buf, sizeof(buf));
+		long n = io_recv(fd, buf, sizeof(buf));
 		if (n <= 0)
 			break;
 	}
 	remove_client(fd);
 }
 
-static void handle_reload_js(int fd)
+static void handle_reload_js(sock_t fd)
 {
 	char header[256];
 	int hlen = snprintf(header, sizeof(header),

@@ -563,12 +787,12 @@ static void handle_reload_js(int fd)
 		"\r\n",
 		sizeof(CLIENT_JS) - 1);
 
-	write(fd, header, (size_t)hlen);
-	write(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1);
-	close(fd);
+	io_send(fd, header, (size_t)hlen);
+	io_send(fd, CLIENT_JS, sizeof(CLIENT_JS) - 1);
+	CLOSESOCK(fd);
 }
 
-static void handle_root(int fd)
+static void handle_root(sock_t fd)
 {
 	char body[256];
 	int blen = snprintf(body, sizeof(body),

@@ -583,30 +807,30 @@ static void handle_root(int fd)
 		"Connection: close\r\n"
 		"\r\n", blen);
 
-	write(fd, header, (size_t)hlen);
-	write(fd, body, (size_t)blen);
-	close(fd);
+	io_send(fd, header, (size_t)hlen);
+	io_send(fd, body, (size_t)blen);
+	CLOSESOCK(fd);
 }
 
-static void handle_not_found(int fd)
+static void handle_not_found(sock_t fd)
 {
 	static const char resp[] =
 		"HTTP/1.1 404 Not Found\r\n"
 		"Content-Length: 0\r\n"
 		"Connection: close\r\n"
 		"\r\n";
-	write(fd, resp, sizeof(resp) - 1);
-	close(fd);
+	io_send(fd, resp, sizeof(resp) - 1);
+	CLOSESOCK(fd);
 }
 
 static void *connection_thread(void *arg)
 {
-	int fd = (int)(intptr_t)arg;
+	sock_t fd = (sock_t)(intptr_t)arg;
 
 	char buf[4096];
-	ssize_t n = recv(fd, buf, sizeof(buf) - 1, 0);
+	long n = io_recv(fd, buf, sizeof(buf) - 1);
 	if (n <= 0) {
-		close(fd);
+		CLOSESOCK(fd);
 		return NULL;
 	}
 	buf[n] = '\0';

@@ -627,18 +851,18 @@ static void *connection_thread(void *arg)
 	return NULL;
 }
 
-static int g_listen_fd = -1;
+static sock_t g_listen_fd = SOCK_INVALID;
 
-static int start_http_server(void)
+static sock_t start_http_server(void)
 {
-	int srv = socket(AF_INET, SOCK_STREAM, 0);
-	if (srv < 0) {
-		perror("socket");
-		return -1;
+	sock_t srv = socket(AF_INET, SOCK_STREAM, 0);
+	if (srv == SOCK_INVALID) {
+		socket_perror("socket");
+		return SOCK_INVALID;
 	}
 
 	int yes = 1;
-	setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
+	setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(yes));
 
 	struct sockaddr_in addr = { 0 };
 	addr.sin_family = AF_INET;

@@ -646,15 +870,15 @@ static int start_http_server(void)
 	addr.sin_port = htons(g_port);
 
 	if (bind(srv, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
-		perror("bind");
-		close(srv);
-		return -1;
+		socket_perror("bind");
+		CLOSESOCK(srv);
+		return SOCK_INVALID;
 	}
 
 	if (listen(srv, 32) < 0) {
-		perror("listen");
-		close(srv);
-		return -1;
+		socket_perror("listen");
+		CLOSESOCK(srv);
+		return SOCK_INVALID;
 	}
 
 	return srv;

@@ -664,35 +888,22 @@ static int start_http_server(void)
  * File change -> rebuild + notify, driven by the watcher thread
  * ------------------------------------------------------------------- */
 
-/* Minimum time between two reload broadcasts. watch_settle() absorbs most
- * self-inflicted events from a -c build writing into the watched tree,
- * but it can't catch everything -- measured on macOS with Spotlight
- * (mdworker) actively indexing the watched folder, a single edit could
- * still produce a second, indistinguishable-from-real change notification
- * 1.3-1.9s after the first (almost certainly Spotlight touching metadata
- * on the just-written files some time after the fact -- moving the
- * settle window or halving the watch-rebuild cost didn't change this
- * gap, which rules out our own rebuild as the source). Rather than chase
- * every possible external trigger, rate-limit the visible effect instead:
- * if a reload was just sent, skip sending another one for a cooldown
- * comfortably above that observed gap. The build still runs every time
- * (cheap, and keeps output current); only the duplicate reload is
- * suppressed. Trade-off: two genuine edits saved within the cooldown of
- * each other will only visibly reload once, showing the first save's
- * content until a later change arrives -- acceptable for a dev tool. */
-#define RELOAD_COOLDOWN_MS 2500
-
-static struct timespec g_last_broadcast;
+/* Minimum time between two reload broadcasts. Root-caused the double-fire
+ * this was originally added to paper over: it was NOTE_ATTRIB (see
+ * kq_add_path) picking up an atime bump from something merely reading a
+ * just-written file (e.g. Spotlight/mdworker indexing it), not a race in
+ * write detection or our own -c build's writes -- dropping NOTE_ATTRIB and
+ * watch_settle() together were enough on their own (confirmed: zero
+ * duplicate reloads with this cooldown effectively disabled). This stays
+ * on as a cheap safety net for whatever's left uncaught (inotify's
+ * IN_ATTRIB has the same class of issue; the poll fallback has none of
+ * this, but costs nothing to also guard), kept short enough that it
+ * shouldn't ever visibly swallow a genuine rapid second edit. */
+#define RELOAD_COOLDOWN_MS 150
+
+static long long g_last_broadcast_ms = 0;
 static bool g_have_last_broadcast = false;
 
-static long ms_since(const struct timespec *from)
-{
-	struct timespec now;
-	clock_gettime(CLOCK_MONOTONIC, &now);
-	return (now.tv_sec - from->tv_sec) * 1000 +
-		(now.tv_nsec - from->tv_nsec) / 1000000;
-}
-
 static void on_change(void)
 {
 	printf("[liveside] change detected\n");

@@ -707,13 +918,14 @@ static void on_change(void)
 		}
 	}
 
-	if (g_have_last_broadcast && ms_since(&g_last_broadcast) < RELOAD_COOLDOWN_MS) {
+	if (g_have_last_broadcast &&
+	    (now_ms() - g_last_broadcast_ms) < RELOAD_COOLDOWN_MS) {
 		printf("[liveside] reload sent recently, skipping duplicate\n");
 		return;
 	}
 
 	broadcast_reload();
-	clock_gettime(CLOCK_MONOTONIC, &g_last_broadcast);
+	g_last_broadcast_ms = now_ms();
 	g_have_last_broadcast = true;
 }
 

@@ -767,6 +979,15 @@ static void usage(const char *prog)
 
 int main(int argc, char **argv)
 {
+#ifdef _WIN32
+	WSADATA wsa;
+	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
+		fprintf(stderr, "[liveside] WSAStartup failed\n");
+		return 1;
+	}
+#endif
+	mutex_init(&g_clients_mu);
+
 	int opt;
 	while ((opt = getopt(argc, argv, "p:d:c:i:h")) != -1) {
 		switch (opt) {

@@ -791,7 +1012,11 @@ int main(int argc, char **argv)
 
 	signal(SIGINT, handle_sigint);
 	signal(SIGTERM, handle_sigint);
+#ifndef _WIN32
+	/* No SIGPIPE on Windows -- a broken socket write there just returns
+	 * an error, no signal to ignore. */
 	signal(SIGPIPE, SIG_IGN);
+#endif
 
 	printf("[liveside] watching '%s'\n", g_watch_dir);
 	printf("[liveside] SSE endpoint: http://localhost:%d/livereload\n",

@@ -802,14 +1027,14 @@ int main(int argc, char **argv)
 		printf("[liveside] build command: %s\n", g_build_cmd);
 
 	g_listen_fd = start_http_server();
-	if (g_listen_fd < 0)
+	if (g_listen_fd == SOCK_INVALID)
 		return 1;
 
-	pthread_t watcher, pinger;
-	pthread_create(&watcher, NULL, watcher_loop, NULL);
-	pthread_detach(watcher);
-	pthread_create(&pinger, NULL, ping_thread, NULL);
-	pthread_detach(pinger);
+	thread_t watcher, pinger;
+	thread_spawn(&watcher, watcher_loop, NULL);
+	thread_detach(watcher);
+	thread_spawn(&pinger, ping_thread, NULL);
+	thread_detach(pinger);
 
 	while (g_running) {
 		/* accept() blocking indefinitely can't be woken up reliably from

@@ -822,18 +1047,21 @@ int main(int argc, char **argv)
 		if (pr <= 0)
 			continue;
 
-		int fd = accept(g_listen_fd, NULL, NULL);
-		if (fd < 0)
+		sock_t fd = accept(g_listen_fd, NULL, NULL);
+		if (fd == SOCK_INVALID)
 			continue;
 		int yes = 1;
-		setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
+		setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes));
 
-		pthread_t conn;
-		pthread_create(&conn, NULL, connection_thread, (void *)(intptr_t)fd);
-		pthread_detach(conn);
+		thread_t conn;
+		thread_spawn(&conn, connection_thread, (void *)(intptr_t)fd);
+		thread_detach(conn);
 	}
 
-	close(g_listen_fd);
+	CLOSESOCK(g_listen_fd);
 	printf("\n[liveside] shutting down\n");
+#ifdef _WIN32
+	WSACleanup();
+#endif
 	return 0;
 }