如何在 C 程序中监控 NIC 状态(启动/关闭)而不轮询内核?
现在我需要实时获取网卡的状态(启动或关闭)。这意味着当网卡在阻塞循环中启动或关闭时,我必须捕获内核中断。
我的第一个愚蠢的方法是检查 /sys/class/net/eth0/operstate 或使用 ioctl
一旦我注意到inotify函数可以以块模式监视文件。但不幸的是,它无法监视 /sys/class/net/eth0/operstate 文件,因为 /sys 位于 RAM 中而不是磁盘中。
那么,除了编写内核模块以块模式捕获C程序中的NIC中断(上/下)之外,还有其他方法吗?
Now I need to get the status of the NIC(up or down) in the real time. That means I have to catch the kernel interrupt when the NIC up or down in a blocked loop.
The first stupid method from mine is that check on the /sys/class/net/eth0/operstate or use ioctl to get the ifflag every 100ms in a loop. But 100ms is too long for the app to reroute the traffic and also polling kernel every 100ms is not good idea.
Once I notice the inotify function that can monitor the files in a block mode. But unfortunately, it can't monitor the /sys/class/net/eth0/operstate file since /sys is located in the RAM not in the disk.
So, is there any methods except writing a kernel module to catch the NIC interrupt(up/down) in the C program with a block mode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,打开一个 netlink 套接字并侦听 RTMGRP_LINK(网络接口创建/删除/启动/关闭事件)多播组。
netlink 手册页此处有一个具体的示例来执行此操作。
Yes, open a netlink socket and listen to the RTMGRP_LINK (network interface create/delete/up/down events) multicast groups.
The netlink man page here has a specific example to do this.
在网上做了一些研究/阅读后,我设法编写了一个工作代码来监视网卡状态。
After doing a little research/reading on the web, I managed to cook up a working code to monitor NIC status.
您是否尝试过使用
select
或poll
函数监控/sys/class/net/eth0/operstate
文件?据我所知,sysfs 文件在轮询方面应与常规文件相同:每当发生更改时,您都应该在文件句柄上收到通知,表明某些内容已更改,并且您应该能够做出相应的回应。Have you tried monitoring the
/sys/class/net/eth0/operstate
file withselect
orpoll
function? As far as I can tell sysfs files should behave the same with respect to polling as regular files: whenever a change occurs you should get a notification on the file handle that something has changed and you should be able to respond accordingly.