Permalink
Browse files

Add statsd_finalize for deallocating resources

  • Loading branch information...
1 parent c54ce5b commit a07eadf057d17da672d4db5bfe31a515c79065ec @romanbsd committed Apr 13, 2012
Showing with 19 additions and 4 deletions.
  1. +17 −4 statsd-client.c
  2. +1 −0 statsd-client.h
  3. +1 −0 test-client.c
View
@@ -3,6 +3,7 @@
#include <stdlib.h>
#include <netdb.h>
#include <time.h>
+#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
@@ -13,12 +14,12 @@
static int sock = -1;
static struct sockaddr_in server;
-static char *ns = "";
+static char *ns = NULL;
int statsd_init_with_namespace(const char *host, int port, const char *ns_)
{
size_t len = strlen(ns_);
- if (strlen(ns) > 0) {
+ if (ns) {
free(ns);
}
if ( (ns = malloc(len + 2)) == NULL ) {
@@ -67,6 +68,18 @@ int statsd_init(const char *host, int port)
return 0;
}
+void statsd_finalize()
+{
+ if (sock != -1) {
+ close(sock);
+ sock = -1;
+ }
+ if (ns) {
+ free(ns);
+ ns = NULL;
+ }
+}
+
/* will change the original string */
static void cleanup(char *stat)
{
@@ -106,9 +119,9 @@ static void send_stat(char *stat, size_t value, const char *type, float sample_r
cleanup(stat);
if (sample_rate == 1.0) {
- snprintf(message, MAX_MSG_LEN, "%s%s:%zd|%s", ns, stat, value, type);
+ snprintf(message, MAX_MSG_LEN, "%s%s:%zd|%s", ns ? ns : "", stat, value, type);
} else {
- snprintf(message, MAX_MSG_LEN, "%s%s:%zd|%s|@%.2f", ns, stat, value, type, sample_rate);
+ snprintf(message, MAX_MSG_LEN, "%s%s:%zd|%s|@%.2f", ns ? ns : "", stat, value, type, sample_rate);
}
send_to_socket(message);
}
View
@@ -4,6 +4,7 @@
int statsd_init(const char *host, int port);
int statsd_init_with_namespace(const char *host, int port, const char *ns);
+void statsd_finalize(void);
void statsd_inc(char *stat, float sample_rate);
void statsd_dec(char *stat, float sample_rate);
View
@@ -16,6 +16,7 @@ int main(void)
for(i=0; i<10; i++) {
statsd_count("count3", i, 0.8);
}
+ statsd_finalize();
return 0;
}

0 comments on commit a07eadf

Please sign in to comment.