请将下面的程序改为非阻塞 接收 #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 19:07:50 浏览: 83
非阻塞模式socket程序
5星 · 资源好评率100%
可以使用非阻塞方式来接收消息,使用fcntl函数设置socket为非阻塞模式。在接收数据之前,使用select函数来检查是否有数据可以读取,如果有则接收数据,否则继续等待。修改后的代码如下:
```
#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/select.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;
}
fcntl(fd, F_SETFL, O_NONBLOCK);
fd_set rfds;
char buf[UEVENT_BUFFER_SIZE];
while (1) {
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
int ret = select(fd + 1, &rfds, NULL, NULL, NULL);
if (ret == -1) {
perror("Failed to select socket");
close(fd);
return EXIT_FAILURE;
}
else if (ret) {
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;
}
```
阅读全文