Last active
July 23, 2019 04:27
-
-
Save kkumar-fk/7b4587eb1a1c501961226322514d42ef to your computer and use it in GitHub Desktop.
Server program to benchmark so_reuseport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
#include <netdb.h> | |
void create_children(int nprocs, int parent_pid) | |
{ | |
while (nprocs-- > 0) { | |
if (getpid() == parent_pid && fork() < 0) | |
exit(1); | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int reuse_port, fd, cfd, nprocs, opt = 1, parent_pid = getpid(); | |
struct sockaddr_in server; | |
if (argc != 4) { | |
fprintf(stderr, "Port# #Procs {0->fork, or 1->SO_REUSEPORT}\n"); | |
return 1; | |
} | |
nprocs = atoi(argv[2]); | |
reuse_port = atoi(argv[3]); | |
if (reuse_port) /* proper SO_REUSEPORT */ | |
create_children(nprocs, parent_pid); | |
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { | |
perror("socket"); | |
return 1; | |
} | |
if (reuse_port) | |
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (char *)&opt, sizeof opt); | |
server.sin_family = AF_INET; | |
server.sin_addr.s_addr = INADDR_ANY; | |
server.sin_port = htons(atoi(argv[1])); | |
if (bind(fd, (struct sockaddr *)&server, sizeof server) < 0) { | |
perror("bind"); | |
return 1; | |
} | |
if (!reuse_port) /* simple fork instead of SO_REUSEPORT */ | |
create_children(nprocs, parent_pid); | |
if (parent_pid == getpid()) { | |
while (wait(NULL) != -1); /* wait for all children */ | |
} else { | |
listen(fd, SOMAXCONN); | |
while (1) { | |
if ((cfd = accept(fd, NULL, NULL)) < 0) { | |
perror("accept"); | |
return 1; | |
} | |
close(cfd); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment