Skip to content

Instantly share code, notes, and snippets.

@benaryorg
Last active September 27, 2018 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benaryorg/4897ce5fe7cdb27cb8d86a6fef318789 to your computer and use it in GitHub Desktop.
Save benaryorg/4897ce5fe7cdb27cb8d86a6fef318789 to your computer and use it in GitHub Desktop.
// somewhat performant discard service I guess.
// listens on localhost:1337 (it's not port 9 since I prefer non-priv users)
//
// compile with something like that:
// clang -Wall -Wextra -Werror -pedantic -std=c11 -O2 -o discard discard.c
#include <err.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
void sigchld(int sig)
{
(void)sig;
int status;
if(waitpid(-1,&status,WNOHANG) == -1)
{
err(EXIT_FAILURE,"waitpid");
}
}
int main(int argc,char **argv)
{
if(argc > 1)
{
errx(EXIT_FAILURE,"Usage: %s",argv[0]);
}
struct addrinfo hints;
struct addrinfo *result,*rp;
int n;
pid_t pid;
memset(&hints,0,sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
n = getaddrinfo("localhost","1337",&hints,&result);
if(n != 0)
{
errx(EXIT_FAILURE,"getaddrinfo: %s",gai_strerror(n));
}
int server;
for(rp = result;rp != NULL;rp = rp->ai_next)
{
server = socket(rp->ai_family,rp->ai_socktype,rp->ai_protocol);
if(server == -1)
{
warn("socket");
continue;
}
int optval = 1;
setsockopt(server,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof optval);
if(bind(server,rp->ai_addr,rp->ai_addrlen) == 0)
{
break;
}
warn("bind");
close(server);
}
if(rp == NULL)
{
errx(EXIT_FAILURE,"Could not bind");
}
freeaddrinfo(result);
listen(server,4);
signal(SIGCHLD,sigchld);
for(;;)
{
int them = accept(server,NULL,NULL);
if(them < 0)
{
warn("accept");
continue;
}
if((pid=fork()))
{
if(pid < 0)
{
err(EXIT_FAILURE,"fork");
}
close(them);
continue;
}
int devnull = open("/dev/null",O_WRONLY);
while((n = sendfile(devnull,them,0,0x8000000)) > 0);
if(n < 0)
{
warn("sendfile");
}
close(them);
close(devnull);
err(EXIT_SUCCESS,"prnt");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment