Created
July 6, 2020 15:45
-
-
Save nanpuyue/5b675470ed983c56ce7464d5a245bcd3 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
// date: 2020-07-06 | |
// license: GPLv3 https://www.gnu.org/licenses/gpl-3.0.txt | |
// author: nanpuyue <[email protected]> https://blog.nanpuyue.com | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
#include <fcntl.h> | |
#include <sys/epoll.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#define MAX_EVENTS 10 | |
void fail(const char *desc) | |
{ | |
perror(desc); | |
exit(EXIT_FAILURE); | |
} | |
void set_nonblock(int fd) | |
{ | |
int flags = fcntl(fd, F_GETFL); | |
if (flags == -1) | |
fail("fcntl(F_GETFL)"); | |
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) | |
fail("fcntl(F_SETFL)"); | |
} | |
int connect_socket(const char *ip, int port) | |
{ | |
int fd = socket(AF_INET, SOCK_STREAM, 6); | |
if (fd < 0) | |
fail("socket"); | |
struct sockaddr_in addr; | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(port); | |
if (inet_pton(AF_INET, ip, &addr.sin_addr) == 0) | |
{ | |
printf("inet_pton: Invalid address"); | |
exit(EXIT_FAILURE); | |
} | |
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) | |
fail("connect"); | |
set_nonblock(fd); | |
return fd; | |
} | |
int main() | |
{ | |
struct epoll_event event, events[MAX_EVENTS]; | |
int epfd, socket, ready; | |
epfd = epoll_create1(0); | |
if (epfd == -1) | |
fail("epoll_create1"); | |
socket = connect_socket("127.0.0.1", 8000); | |
event.events = EPOLLRDHUP; | |
event.data.fd = socket; | |
if (epoll_ctl(epfd, EPOLL_CTL_ADD, socket, &event) == -1) | |
fail("epoll_ctl(EPOLL_CTL_ADD)"); | |
for (;;) | |
{ | |
ready = epoll_wait(epfd, events, MAX_EVENTS, -1); | |
if (ready == -1) | |
fail("epoll_wait"); | |
for (int i = 0; i < ready; ++i) | |
{ | |
if (events[i].data.fd == socket) | |
{ | |
printf("events: 0x%x\n", events[i].events); | |
exit(EXIT_SUCCESS); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment