Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fcntl.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/epoll.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <unistd.h>
- #define SOCK_PATH "test_socket"
- #define MAX_EVENTS 10
- /* make gcc -std=c99 -g3 -Wall -o client client.c */
- int
- main(void)
- {
- int sockfd, epollfd;
- struct sockaddr_un server;
- struct epoll_event ev;
- char buf[1024];
- sockfd = socket(AF_UNIX, SOCK_DGRAM, 0);
- if (sockfd == -1) {
- printf("SOCKET ERROR = %d\n", errno);
- exit(1);
- }
- epollfd = epoll_create(1024);
- if (epollfd < 0) {
- printf("epoll failed %d: %s", errno, strerror(errno));
- exit(1);
- }
- // notify on EPOLLOUT events (ie: fd becomes writable) with edge-triggered behavior
- ev.events = EPOLLOUT | EPOLLHUP | EPOLLERR | EPOLLET;
- ev.data.fd = sockfd;
- if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
- perror("epoll_ctl: sockfd");
- exit(EXIT_FAILURE);
- }
- // combine edge-triggered epolling with non-blocking sockets
- if (fcntl(sockfd, F_SETFL, O_NONBLOCK) < 0) {
- printf("fcntl F_SETFL failed.%s", strerror(errno));
- exit(1);
- }
- memset(&server, 0, sizeof(struct sockaddr_un));
- server.sun_family = AF_UNIX;
- strcpy(server.sun_path, SOCK_PATH);
- for (unsigned i = 0; ; i++) {
- struct epoll_event events[MAX_EVENTS];
- int nfds = epoll_wait(epollfd, events, MAX_EVENTS, -1);
- if (nfds == -1) {
- perror("epoll_wait");
- exit(EXIT_FAILURE);
- }
- for (unsigned n = 0; n < nfds; n++) {
- if (events[n].data.fd != sockfd) {
- continue;
- }
- if (events[n].events & EPOLLHUP) {
- printf("EPOLLUP! events is %u\n", events[n].events);
- exit(1);
- }
- if (events[n].events & EPOLLERR) {
- printf("EPOLLERR! events is %u\n", events[n].events);
- exit(1);
- }
- if (!(events[n].events & EPOLLOUT)) {
- exit(1);
- }
- strcpy(buf, "this is a message in a buffer over unix datagrams\n");
- if (i % 10000 == 0) {
- printf("Sent %u packets\n", i);
- printf("events is %u\n", (unsigned)(events[n].events));
- }
- while (1) {
- int r = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *) &server, sizeof(server));
- int err = errno;
- if (r == -1 && err == EAGAIN) {
- // eagain means we should break and wait
- break;
- } else if (r == -1 && err == ECONNREFUSED) {
- // connrefused is ok
- continue;
- } else if (r == -1 && err == ENOENT) {
- // enoent is ok
- continue;
- } else if (r == -1) {
- printf("sendto failed with %d: %s\n", err, strerror(errno));
- exit(1);
- }
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement