Monthly Archive for April, 2016

Extending Nagios functionality with libnagios

Have you ever attempted to write a function in C to execute a command and parse the output? I think I’d rather just let the Nagios library do the heavy lifting for me.

This blog post is going to cover the basics of compiling libnagios, and linking the Nagios library to your application. I’ll be focusing on using some of the built-in Nagios functionality, specifically the runcmd_open() function.

I’m going to assume you have a sane build environment set up (where tools like make and ./configure are working) before we go any further. If you are following along, now would be the time to get these in order.

First, download the source code and extract it. You can get a copy of the Nagios Core source at Once you’ve downloaded it and extracted the files, open up nagioscore-master/lib/runcmd.h ( Search for “extern int runcmd_open”, as of the time of this writing, that should bring you to line 77, where our function is declared:


So what does all that mean? It means we need a command to execute, a file descriptor for stdout, another filedescriptor for stderr. Our application doesn’t need a callback function to register iobrokers or a value to pass. But, since these are declared non null, we’ll have to get creative.

Let’s create a file, named test.c in the root of the nagioscore-master directory. First, we need to include our libnagios header.


Then we define our fake iobroker_register function. This is essentially just a placeholder, as we aren’t (yet) particularly interested in assigning a function to execute when our stdout/stderr stops reading.


Next, we set up our variables that we’ll be using to pass to the runcmd_open() function. We don’t need an env variable, since that argument can accept a NULL value, we’re just going to pass that in (especially since it is unused anyway).


Now we execute runcmd_open(), and let the Nagios library do its magic! This will put stdout in pfd[0] and stderr in pfderr[0].


Let’s copy the stdout to our out var and print some information relating to the command we executed and that command’s output.


Finally, we clean up our memory and exit the program.


Here’s the file in its entirety:



Let’s see it in action! First we’re going to compile our Nagios library! Open up your terminal and let’s get to library compilin’:


Those commands should have compiled your Nagios library and then placed it in /usr/local/nagios/lib. Now, we’re finally ready to compile our program:


Now, if everything went well up this point, you should be able to execute our basic program with the following command:

Your output should be similar to the following:

I hope that you’ve learned a few things about using the Nagios library in your own code. Questions, comments, and suggestions for future posts are all welcome below in the comments section.


– Bryan Heden