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?
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.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.