Stop socket listener when terminating by SIGTERM

- During the termination, StatsService is stopped while
StatsSocketListener is still running.
- This could cause invalid thread access.

Bug: 147316537
Test: Run a test app which keeps sending StatsLog and repeatedly execute
adb shell su root kill `pidof statsd`. statsd should not crash.

Change-Id: Iedd2dcb892f704bdba9adc864afa696de64b8e4c
diff --git a/cmds/statsd/src/main.cpp b/cmds/statsd/src/main.cpp
index e394533..cd9c4e5 100644
--- a/cmds/statsd/src/main.cpp
+++ b/cmds/statsd/src/main.cpp
@@ -37,6 +37,7 @@
 using std::make_shared;
 
 shared_ptr<StatsService> gStatsService = nullptr;
+sp<StatsSocketListener> gSocketListener = nullptr;
 
 void signalHandler(int sig) {
     if (sig == SIGPIPE) {
@@ -47,6 +48,7 @@
         return;
     }
 
+    if (gSocketListener != nullptr) gSocketListener->stopListener();
     if (gStatsService != nullptr) gStatsService->Terminate();
     ALOGW("statsd terminated on receiving signal %d.", sig);
     exit(1);
@@ -92,11 +94,11 @@
 
     gStatsService->Startup();
 
-    sp<StatsSocketListener> socketListener = new StatsSocketListener(eventQueue);
+    gSocketListener = new StatsSocketListener(eventQueue);
 
     ALOGI("Statsd starts to listen to socket.");
     // Backlog and /proc/sys/net/unix/max_dgram_qlen set to large value
-    if (socketListener->startListener(600)) {
+    if (gSocketListener->startListener(600)) {
         exit(1);
     }