Page MenuHomeFreeBSD
Authored By
vico13.chen_gmail.com
Aug 9 2021, 9:58 AM
Size
2 KB
Referenced Files
None
Subscribers
None

epoll_hup.c

#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include <pthread.h>
static int
set_cloexec_or_close(int fd)
{
long flags;
if (fd == -1)
return -1;
flags = fcntl(fd, F_GETFD);
if (flags == -1)
goto err;
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)
goto err;
return fd;
err:
close(fd);
return -1;
}
static int
wl_os_epoll_create_cloexec(void)
{
int fd;
fd = epoll_create1(EPOLL_CLOEXEC);
if (fd >= 0)
return fd;
if (errno != EINVAL)
return -1;
fd = epoll_create(1);
return set_cloexec_or_close(fd);
}
int fds[2];
int epoll_fd;
static int
setup_launcher_socket(void)
{
if (socketpair(AF_LOCAL, SOCK_SEQPACKET, 0, fds) < 0) {
fprintf(stderr, "weston: socketpair failed: %s\n",
strerror(errno));
return -1;
}
/*
if (fcntl(fds[0], F_SETFD, FD_CLOEXEC) < 0) {
fprintf(stderr, "weston: fcntl failed: %s\n",
strerror(errno));
return -1;
} */
return 0;
}
static void
add_source()
{
struct epoll_event ep;
memset(&ep, 0, sizeof ep);
//ep.events = EPOLLIN | EPOLLRDHUP;
ep.events = EPOLLRDHUP;
ep.data.fd = fds[0];
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fds[0], &ep) < 0)
fprintf(stderr, "Failed add to epoll\n");
}
#define ARRAY_LENGTH(xx) (sizeof(xx) / sizeof(xx[0]))
static int
wl_event_loop_dispatch()
{
struct epoll_event ep[32];
int i, count, size = 0;
char buffer[1024];
count = epoll_wait(epoll_fd, ep, ARRAY_LENGTH(ep), -1);
//count = epoll_wait(epoll_fd, ep, ARRAY_LENGTH(ep), 3000);
fprintf(stderr, "count=%d\n", count);
if (count < 0)
return 0;
for (i = 0; i < count; i++) {
fprintf(stderr, "fd eventmask %x == fd=%d\n",
ep[i].events, ep[i].data.fd);
size = read(ep[i].data.fd, buffer, sizeof buffer);
fprintf(stderr, "read %d: %s\n", size, buffer);
}
return size;
}
static void *
worker_thread_function(void *data)
{
#define hello "hello world\n"
char buffer[1000];
int l;
l = read(fds[1], buffer, sizeof(buffer));
fprintf(stderr, "%s: read %d: %s\n", __func__, l, buffer);
write(fds[1], hello, sizeof hello);
sleep(3);
close(fds[1]);
return 0;
}
int
main(int argc, char **argv)
{
int times = 0;
char buffer[1024];
pthread_t tid;
epoll_fd = wl_os_epoll_create_cloexec();
setup_launcher_socket();
add_source();
do {
snprintf(buffer, sizeof buffer, "hellow orld%d\n", times++);
write(fds[0], buffer, strlen(buffer) + 1);
pthread_create(&tid, NULL, worker_thread_function, 0);
while (wl_event_loop_dispatch());
} while (0);
}

File Metadata

Mime Type
text/x-c
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3997090
Default Alt Text
epoll_hup.c (2 KB)

Event Timeline