It's necessary to do serious checks for the memory leaks using tools like valgrind. This patch tries to implement a graceful exit for all tvheadend components and free allocated memory. Also, some memory leaks were fixed.
this is being used within IPTV code, and eventually I might make this a bit more generic so I can use from elsewhere, like imagecache.