如何在不轮询内核的情况下监视 C 程序中的 NIC 状态(启动/关闭)? [英] How can I monitor the NIC status(up/down) in a C program without polling the kernel?

查看:24
本文介绍了如何在不轮询内核的情况下监视 C 程序中的 NIC 状态(启动/关闭)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我需要实时获取网卡的状态(开启或关闭).这意味着当 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.

我的第一个愚蠢的方法是检查 /sys/class/net/eth0/operstate 或使用 ioctl 在循环中每 100 毫秒获取一次 ifflag.但是 100 毫秒对于应用重新路由流量来说太长了,而且每 100 毫秒轮询一次内核也不是一个好主意.

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.

有一次我注意到 inotify 函数可以以块模式监视文件.但不幸的是,它无法监控/sys/class/net/eth0/operstate 文件,因为/sys 位于 RAM 中而不是磁盘中.

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.

那么,除了写一个内核模块来用block模式在C程序中捕捉网卡中断(up/down)之外,还有什么方法吗?

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?

推荐答案

是的,打开一个 netlink 套接字并监听 RTMGRP_LINK(网络接口创建/删除/向上/向下事件)多播组.

Yes, open a netlink socket and listen to the RTMGRP_LINK (network interface create/delete/up/down events) multicast groups.

netlink 手册页这里有一个具体的例子这样做.

The netlink man page here has a specific example to do this.

这篇关于如何在不轮询内核的情况下监视 C 程序中的 NIC 状态(启动/关闭)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆