TUT:Simple Perl Async Application

From Net-SNMP Wiki
Jump to: navigation, search

Q: in the documentation i can see that the get function takes a second option argument which is the callback function, how does it work ?

  • as an example...
$result = $sess->get("sysDescr","0", [\&cb1, $sess]);
// or without the session pointer, it would look like:
$result = $sess->get("sysDescr","0", [\&cb1]);
    • cb1 is a function that is called back (and $sess is passed as an argument to it along with the normal ones)
    • after you call the above, it'll return immediately.
    • You need to call SNMP::MainLoop(); to get it to wait for packets to arrive.
    • when packets arrive, the callback will be called.
    • eg
sub cb1{
  my $sess = shift; // only if you passed sess above
  my $vlist = shift;
  // ...
    • you can have mulitple outstanding requests (ie, call get() on a bunch of requests and they'll all be sent out and the callback will be called multiple times)


Q: so the callback function receives two arguments?

  • it receives 1 + anything else you pass it. (in the example above, it passes it a "sess" pointer so it gets it back.) normally it's just the varbind list.


Other code you can look at:

  • np-collectd in the net-policy project
  • perl/SNMP/SNMP.pm in "gettable"
  • perl/SNMP/t/async.t [worst case :-)]

Also run "perldoc SNMP", and read the section on "Acceptable callback formats"