Last active
January 26, 2024 08:39
-
-
Save gitsrc/af9d8790bba657992d9e50a2f1dda241 to your computer and use it in GitHub Desktop.
posix-queue-epoll-server
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 <stdio.h> | |
#include <mqueue.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> //for close | |
#include <sys/epoll.h> // for epoll_create1(), epoll_ctl(), struct epoll_event | |
#define PATH_URI "/corermanipc" | |
#define MAX_LEN 2000 | |
#define MAX_EVENTS 5 | |
#define TIME_OUT 30000 | |
int main() { | |
char *info = (char *) malloc(sizeof(char) * MAX_LEN); | |
int recvlen = 0; | |
mqd_t mqd = mq_open(PATH_URI, O_CREAT | O_RDWR | O_NONBLOCK, 0x660, NULL); | |
if (mqd == -1) { | |
printf("MQ open faild : %s\n", strerror(errno)); | |
} else { | |
int epoll_fd = epoll_create1(0); | |
if (epoll_fd == -1) { | |
printf("epoll create faild : %s\n", strerror(errno)); | |
} else { | |
struct epoll_event event, events[MAX_EVENTS]; | |
event.events = EPOLLIN; | |
event.data.fd = mqd; | |
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mqd, &event)) { | |
printf("epoll ctl faild : %s\n", strerror(errno)); | |
close(epoll_fd); | |
} | |
int event_count, i; | |
struct mq_attr mqatt; | |
mq_getattr(mqd, &mqatt); | |
while (1) { | |
event_count = epoll_wait(epoll_fd, events, MAX_EVENTS, TIME_OUT); | |
for (i = 0; i < event_count; i++) { | |
if (events[i].data.fd == mqd) { | |
recvlen = mq_receive(mqd, info, mqatt.mq_msgsize, NULL); | |
if (recvlen != -1) { | |
printf("%s\n", info); | |
} else { | |
printf("epoll recv faild : %s\n", strerror(errno)); | |
} | |
} | |
} | |
} | |
} | |
} | |
free(info); | |
mq_close(mqd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment