diff --git a/src/Makefile b/src/Makefile
index 6f549977d1de3dd243067acbd4338b8e42194fda..2b875b4e07484320edc6131b580d8aed23492bda 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -27,7 +27,7 @@ CXXFLAGS = -std=c++11 -Wall -Wextra -O0 -g -rdynamic -Wconversion
 #CXXFLAGS = -std=c++11 -Wall -Wextra -g -rdynamic
 
 CFLAGS = $(CXXFLAGS)
-LDFLAGS = -ltbb -ltbbmalloc -lboost_thread -lcurl -pthread
+LDFLAGS = -ltbb -ltbbmalloc -lboost_thread -lboost_chrono -lcurl -pthread
 
 CPPFLAGS = -I. -Iwzdma
 
diff --git a/src/scdaq.cc b/src/scdaq.cc
index 14b8fc0dd0a301f13a2af7275e86eca1357b1e78..917609abb38a6bf4aa842a12eb197e87b597c5eb 100644
--- a/src/scdaq.cc
+++ b/src/scdaq.cc
@@ -104,6 +104,7 @@ int run_pipeline( int nbThreads, ctrl& control, config& conf )
 int main( int argc, char* argv[] ) {
   (void)(argc);
   (void)(argv);
+  int retval = 0;
 
 if(argc < 2){
 		LOG(DEBUG) << "no arguments provided to scdaq, try --help";
@@ -131,7 +132,7 @@ if(argc < 2){
   try {
     config conf(argv[2]);
     conf.print();
-    LOG(DEBUG) << "configuration loaded";
+    LOG(DEBUG) << "Configuration loaded";
     ctrl control;
     //    tbb::tick_count mainStartTime = tbb::tick_count::now();
 
@@ -155,15 +156,32 @@ if(argc < 2){
 
     int nbThreads = conf.getNumThreads();
 
-    tbb::task_scheduler_init init( nbThreads );
-    if (!run_pipeline (nbThreads, control, conf))
-      return 1;
+    retval = 0;
+    try {
+      tbb::task_scheduler_init init( nbThreads );
+      if (!run_pipeline (nbThreads, control, conf)) {
+        retval = 1;
+        // Will terminate with errorocde set
+      }
+    } catch(std::exception& e) {
+      LOG(ERROR) << "Error in pipelines. Error text is: \"" << e.what() << "\"";
+      retval = 1;
+      // Will terminate with errorocde set
+    }
+
+    LOG(DEBUG) << "Terminating the internal TCP server.";
+    io_service.stop();
+    if (!t.try_join_for(boost::chrono::milliseconds(2000))) {
+      LOG(ERROR) << "Failed to terminate the internal TCP server, the program may crash on exit.";
+    } else {
+      LOG(DEBUG) << "Internal TCP server is terminated.";
+    }
 
     //    utility::report_elapsed_time((tbb::tick_count::now() - mainStartTime).seconds());
+    return retval;
 
-    return 0;
   } catch(std::exception& e) {
-    LOG(ERROR) << "error occurred. error text is :\"" << e.what() << "\"";
+    LOG(ERROR) << "Error occurred. error text is: \"" << e.what() << "\"";
     return 1;
   }
 }