请使用epoll将下面的程序改为非阻塞 接收 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/netlink.h> #include <sys/socket.h> #define UEVENT_BUFFER_SIZE 2048 int main(int argc, char **argv) { int fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT); if (fd < 0) { perror("Failed to create socket"); return EXIT_FAILURE; } struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; addr.nl_groups = NETLINK_KOBJECT_UEVENT; if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Failed to bind socket"); close(fd); return EXIT_FAILURE; } char buf[UEVENT_BUFFER_SIZE]; while (1) { ssize_t n = recv(fd, buf, sizeof(buf), 0); if (n < 0) { perror("Failed to receive data"); close(fd); return EXIT_FAILURE; } char *p = buf; while (p < buf + n) { printf("%s\n", p); p += strlen(p) + 1; } } close(fd); return EXIT_SUCCESS; }
时间: 2024-02-14 15:07:50 浏览: 169
以下是使用epoll将程序改为非阻塞接收的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/netlink.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#define UEVENT_BUFFER_SIZE 2048
#define MAX_EVENTS 10
int main(int argc, char **argv)
{
int fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
if (fd < 0) {
perror("Failed to create socket");
return EXIT_FAILURE;
}
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
addr.nl_groups = NETLINK_KOBJECT_UEVENT;
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("Failed to bind socket");
close(fd);
return EXIT_FAILURE;
}
// 创建 epoll 实例
int epfd = epoll_create1(0);
if (epfd < 0) {
perror("Failed to create epoll instance");
close(fd);
return EXIT_FAILURE;
}
// 将 fd 添加到 epoll 实例
struct epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET; // 设置为边沿触发模式
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event) < 0) {
perror("Failed to add fd to epoll");
close(epfd);
close(fd);
return EXIT_FAILURE;
}
char buf[UEVENT_BUFFER_SIZE];
while (1) {
struct epoll_event events[MAX_EVENTS];
int n = epoll_wait(epfd, events, MAX_EVENTS, -1);
if (n < 0) {
perror("Failed to wait for events");
break;
}
for (int i = 0; i < n; i++) {
if (events[i].events & EPOLLIN) {
ssize_t n = recv(fd, buf, sizeof(buf), 0);
if (n < 0) {
perror("Failed to receive data");
break;
}
char *p = buf;
while (p < buf + n) {
printf("%s\n", p);
p += strlen(p) + 1;
}
}
}
}
close(epfd);
close(fd);
return EXIT_SUCCESS;
}
```
主要的改动如下:
1. 创建了一个 epoll 实例,并将 socket fd 添加到 epoll 实例中;
2. 将 while 循环改为 epoll_wait 调用,用于等待事件;
3. 在接收到 EPOLLIN 事件时,调用 recv 函数接收数据。
注意,我们将 epoll 实例设置为边沿触发模式(EPOLLET),这意味着一旦有数据到达,就会触发一次 EPOLLIN 事件,而不是像水平触发模式(EPOLLIN)那样在数据到达时持续触发 EPOLLIN 事件。这样可以避免 epoll_wait 函数一直返回可读事件,从而提高程序的效率。
阅读全文