Skip to content

Instantly share code, notes, and snippets.

@dkg
Created February 5, 2018 00:23
Show Gist options
  • Save dkg/74bbd5fd8217f9ac92db273215c03118 to your computer and use it in GitHub Desktop.
Save dkg/74bbd5fd8217f9ac92db273215c03118 to your computer and use it in GitHub Desktop.
two processes sharing a listening socket
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
/* Author: Daniel Kahn Gillmor <dkg@fifthhorseman.net>
Example listening daemon where two processes share a single socket,
letting the kernel decide which one gets each incomingn connection
This example uses AF_UNIX with SOCK_STREAM but you could use other
families and types as well.
Once it's running, connect to it and read the pid of the process
that answers your connection. Try this multiple times:
socat STDIO UNIX-CONNECT:testing
*/
int main(int argc, char* argv[])
{
struct sockaddr_un addr = {
.sun_family = AF_UNIX,
.sun_path = "testing",
};
int sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == -1) {
fprintf(stderr, "bad socket() %d (%s)\n", errno, strerror(errno));
return 1;
}
if (bind(sock, (struct sockaddr*)(&addr), sizeof(addr))) {
fprintf(stderr, "bad bind() %d (%s)\n", errno, strerror(errno));
return 1;
}
if (listen(sock, 10)) {
fprintf(stderr, "bad listen() %d (%s)\n", errno, strerror(errno));
return 1;
}
if (fork() == -1) {
fprintf(stderr, "bad fork() %d (%s)\n", errno, strerror(errno));
return 1;
}
pid_t p = getpid();
char view[256];
sprintf(view, "pid %d\n", p);
size_t viewsz = strlen(view);
/* at this point there should be two processes, with different pids
with a listening socket */
int h = accept(sock, NULL, 0);
while (h != -1) {
ssize_t wrote = write(h, view, viewsz);
if (wrote != viewsz) {
fprintf(stderr, "bad write() -- wanted %ld, got %lu. %d (%s)",
viewsz, wrote, errno, strerror(errno));
return 1;
}
if (close(h)) {
fprintf(stderr, "bad close() %d (%s)\n", errno, strerror(errno));
return 1;
}
h = accept(sock, NULL, 0);
}
fprintf(stderr, "bad accept() %d (%s)\n", errno, strerror(errno));
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment