Created
September 3, 2019 21:52
-
-
Save lkw657/5ac84c666ea12c1bef7d6e9fecee2ea7 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 <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <sys/un.h> | |
#include <unistd.h> | |
#include <poll.h> | |
#define BUFFLEN 128 | |
int main(int argc, char **argv) { | |
if (argc != 2) { | |
puts("Usage: ./thing <unix socket>"); | |
exit(EXIT_FAILURE); | |
} | |
int sock = socket(AF_UNIX, SOCK_STREAM, 0); | |
if (sock < 0) { | |
perror("Error creating socket"); | |
exit(EXIT_FAILURE); | |
} | |
struct sockaddr_un address = {}; | |
address.sun_family = AF_UNIX; | |
strncpy(address.sun_path, argv[1], sizeof(address.sun_path)/sizeof(address.sun_path[0])); | |
int res = connect(sock, (struct sockaddr *)&address, sizeof(address)); | |
if (res < 0) { | |
perror("Error creating socket"); | |
exit(EXIT_FAILURE); | |
} | |
struct pollfd fds = {}; | |
fds.fd = sock; | |
fds.events = POLLIN; | |
char received[BUFFLEN] = {}; | |
int pos = 0; | |
int got = 0; | |
while (pos < BUFFLEN - 2){ | |
got = recv(sock, received+pos, BUFFLEN-1-pos, 0); | |
if (got < 0) { | |
perror("Error reading"); | |
exit(EXIT_FAILURE); | |
} | |
pos += got; | |
if (received[pos-1] == '\n') break; | |
if (got == 0) { | |
fputs("Error: socket closed before reading newline\n", stderr); | |
exit(EXIT_FAILURE); | |
} | |
poll(&fds, 1, 10000); | |
} | |
if (pos > BUFFLEN-1) { | |
fputs("Error: buffer not long enough\n", stderr); | |
exit(EXIT_FAILURE); | |
} | |
received[pos] = '\0'; | |
printf("%s", received); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment