Freebsd – Executing a command on link state change in freebsd

freebsdnetworking

In freebsd when a cable gets plugged/unplugged the following lines are written to dmesg buffer:

em0: link state changed to DOWN
em0: link state changed to UP

I would like to run a script when either happens but can't find anything exposing these state changes programmatically. Not even C APIs.

I see that ifconfig prints "status: no carrier" and "status: active" depending on whether a cable is connected. But I would prefer to avoid polling as 1) it burns CPU time which is important on a laptop and 2) it might miss changes if the polling interval is too long.

Is there any way to be notified when a cable is plugged and unplugged?

Best Answer

You'll probably want to check out /etc/devd.conf. devd is the primary way on FreeBSD of reacting to kernel/hardware events.

There's an example in there that shows how to match a network UP/DOWN event and run a task, as below, and the man page has some good information.

notify 0 {
    match "system"          "IFNET";
    match "type"            "LINK_UP";
    media-type              "ethernet";
    action "/etc/rc.d/dhclient quietstart $subsystem";
};

http://www.freebsd.org/cgi/man.cgi?query=devd.conf&sektion=5