Created
May 17, 2018 03:00
-
-
Save uilianries/a7057768a99df9c83626cee0ac83c525 to your computer and use it in GitHub Desktop.
Unix Socket and Poll
This file contains hidden or 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 <poll.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <sys/un.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdbool.h> | |
int main(int argc, char* argv[]) { | |
struct pollfd poll_fd; | |
struct sockaddr_un addr; | |
int result; | |
char buffer[256]; | |
poll_fd.fd = socket(AF_UNIX, SOCK_STREAM, 0); | |
if (poll_fd.fd == -1) { | |
perror("Could not create Unix socket"); | |
return EXIT_FAILURE; | |
} | |
poll_fd.events = POLLIN; | |
memset(&addr, 0, sizeof(addr)); | |
addr.sun_family = AF_UNIX; | |
strncpy(addr.sun_path, "/tmp/socket", sizeof(addr.sun_path)-1); | |
result = connect(poll_fd.fd, (struct sockaddr*)&addr, sizeof(addr)); | |
if (result == -1) { | |
perror("Could not connect on socket"); | |
close(poll_fd.fd); | |
return EXIT_FAILURE; | |
} | |
while (true) { | |
result = poll(&poll_fd, 1, -1); | |
if (result == -1) { | |
perror("Could not wait for event."); | |
close(poll_fd.fd); | |
return EXIT_FAILURE; | |
} | |
if (result == 0) { | |
puts("poll timeout."); | |
continue; | |
} | |
if (poll_fd.revents == POLLIN) { | |
memset(buffer, 0, sizeof(buffer)); | |
if (read(poll_fd.fd, buffer, (sizeof(buffer) - 1)) > 0) { | |
printf("Read = %s\n", buffer); | |
} | |
} else { | |
printf("Received event: %d\n", poll_fd.revents); | |
close(poll_fd.fd); | |
return EXIT_FAILURE; | |
} | |
} | |
close(poll_fd.fd); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment