一、udp惊群测试
1、模型
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b6178c760aeb9d9ca38a580daee85eaf.png)
2、代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#define PROCESS_NUM 2
#define MAXEVENTS 1000
int sock_create_bind(int port){
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0){
return -1;
}
return fd;
}
int make_noblocking(int fd){
int val = fcntl(fd, F_GETFL);
val |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, val) < 0){
perror("fcntl set");
return -1;
}
return 0;
}
int main(int argc, char const *argv[])
{
int udp_fd, i;
struct epoll_event *events;
struct iovec iov[1];
struct msghdr msg;
struct sockaddr sa;
char buf[1024];
if (argc < 2){
printf("Input port\n");
exit(1);
}
if ((udp_fd = sock_create_bind(atoi(argv[1]))) < 0){
perror("socket_create_bind error");
exit(errno);
}
if (make_noblocking(udp_fd) < 0){
perror("make_noblocking error");
exit(errno);
}
events = malloc(MAXEVENTS * sizeof(struct epoll_event));
if (!events){
perror("malloc err");
exit(errno);
}
for (i = 0; i < PROCESS_NUM; i ++){
int pid = fork();
if (pid == 0){
int epoll_fd = epoll_create(MAXEVENTS);
if (epoll_fd < 0){
perror("Create epoll err");
exit(errno);
}
struct epoll_event event;
event.events = EPOLLIN | EPOLLET;
event.data.fd = udp_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, udp_fd, &event) < 0){
perror("epoll_ctl err");
exit(errno);
}
while (1){
int num;
num = epoll_wait(epoll_fd, events, MAXEVENTS, -1);
// sleep(1);
printf("process %d get %d events\n", getpid(), num);
for (i = 0; i < num; i ++){
if (!(events[i].events & EPOLLIN)){
printf("get error event\n");
continue;