Created
August 1, 2018 21:20
-
-
Save christianparpart/8b89c9dbfba83478d1308ecc32b9753d to your computer and use it in GitHub Desktop.
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 <thread> | |
#include <stdio.h> | |
#include <signal.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <sys/types.h> | |
static bool running = true; | |
void signalHandler(int signo) { | |
printf("Signal %d (%s) received.\n", signo, strsignal(signo)); | |
running = false; | |
} | |
int main() { | |
std::thread secondary {[]() { | |
int sfd = socket(AF_INET, SOCK_STREAM, 0); | |
sockaddr_in sa; | |
memset(&sa, 0, sizeof(sa)); | |
sa.sin_family = AF_INET; | |
sa.sin_addr.s_addr = htonl(INADDR_ANY); | |
sa.sin_port = 0; | |
bind(sfd, (sockaddr*) &sa, sizeof(sa)); | |
listen(sfd, SOMAXCONN); | |
socklen_t slen = sizeof(sa); | |
getsockname(sfd, (sockaddr*) &sa, &slen); | |
printf("Listening on TCP port %d ...\n", ntohs(sa.sin_port)); | |
while (running) { | |
int cfd = accept(sfd, nullptr, nullptr); | |
if (cfd < 0) { | |
printf("accept() failed. %s\n", strerror(errno)); | |
continue; | |
} | |
static const std::string greeting = "I'm a demo. Do nothing.\n"; | |
write(cfd, greeting.data(), greeting.size()); | |
close(cfd); | |
} | |
printf("Listener thread interrupted. Exiting.\n"); | |
}}; | |
signal(SIGINT, &signalHandler); | |
printf("Send me a SIGINT, so my listener thread can exit ...\n"); | |
secondary.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment