Linux poll() Guide: Multi-Descriptor Monitoring
In Linux, the poll() function is used to monitor multiple file descriptors, allowing for processing when events occur. Here is how it can be used:
- Include header file:
#include <poll.h>
- Define an array of pollfd structures and initialize it.
struct pollfd fds[nfds];
Among them, nfds is the number of file descriptors that need to be monitored.
- Set the event type and object being monitored for each file descriptor.
fds[i].fd = fd; // 监视的文件描述符
fds[i].events = events; // 监视的事件类型,如POLLIN(可读), POLLOUT(可写)
fds[i].revents = 0; // 实际发生的事件类型,由系统填充
- Use the poll() function to listen for events.
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
Timeout is the duration (in milliseconds) for waiting, and it can be set to -1 to indicate an infinite wait.
- Check the return value to determine if an event has occurred.
if (fds[i].revents & POLLIN) {
// 可读事件发生,进行相应处理
}
if (fds[i].revents & POLLOUT) {
// 可写事件发生,进行相应处理
}
// 可以根据其他事件类型进行相应处理
When the poll() function returns, the type of event that actually occurred will be filled in the revents field, and can be determined using bitwise operations.
This is the basic usage method of the poll() function, which can be adjusted and extended according to specific needs.