Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Tiny HTTP server to respond OK on port 9000 - handy for health checks on embedded boxes!
* Based on
int main(int argc, char *argv[])
int countforks = 0;
int waitint;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// If we don't do SO_REUSEADDR, the app fails to start sometime from connections
// of the last instance that are still around and not yet timed out.
int reuseaddr = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(9000);
bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
listen(sockfd, 5);
while (1) {
int cfd = accept(sockfd, 0, 0);
char *s = "HTTP/1.0 200\r\nContent-type:text/plain\r\n\r\nHello world!\r\n";
if (fork()==0) {
write(cfd, s, strlen(s));
shutdown(cfd, SHUT_RDWR);
} else {
// because we listen in the main process the socket ends up open in both the child
// and the parent. We need to close it in the parent to prevent socket leakage.
// We need to waitpid for all child processes to stop us having zombies piling up
int i; for (i=0; i<=countforks; i++) {
if (waitpid(-1, &waitint, WNOHANG)) {
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment