1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "hilog_input_socket_server.h"
17
18 #include <__threading_support>
19 #include <atomic>
20 #include <functional>
21 #include <sys/prctl.h>
22 #include <sys/socket.h>
23 #include <thread>
24 #include <vector>
25
26 namespace OHOS {
27 namespace HiviewDFX {
~HilogInputSocketServer()28 HilogInputSocketServer::~HilogInputSocketServer()
29 {
30 StopServingThread();
31 }
32
RunServingThread()33 HilogInputSocketServer::ServerThreadState HilogInputSocketServer::RunServingThread()
34 {
35 if (m_serverThread.get_id() != std::thread().get_id()) {
36 return ServerThreadState::ALREADY_STARTED;
37 }
38 m_stopServer.store(false);
39 m_serverThread = std::thread(&HilogInputSocketServer::ServingThread, this);
40 if (m_serverThread.get_id() != std::thread().get_id()) {
41 return ServerThreadState::JUST_STARTED;
42 }
43 return ServerThreadState::CAN_NOT_START;
44 }
45
StopServingThread()46 void HilogInputSocketServer::StopServingThread()
47 {
48 if (m_serverThread.get_id() == std::thread().get_id()) {
49 return;
50 }
51 std::thread tmp;
52 std::swap(m_serverThread, tmp);
53 if (tmp.joinable()) {
54 m_stopServer.store(true);
55 tmp.join();
56 }
57 }
58
ServingThread()59 void HilogInputSocketServer::ServingThread()
60 {
61 prctl(PR_SET_NAME, "hilogd.server");
62 int ret;
63 std::vector<char> data(maxPacketLength);
64 #ifndef __RECV_MSG_WITH_UCRED_
65 while ((ret = RecvPacket(data)) >= 0) {
66 if (ret > 0) {
67 m_packetHandler(data, ret);
68 }
69 if (m_stopServer.load()) {
70 break;
71 }
72 }
73 #else
74 ucred cred;
75 while ((ret = RecvPacket(data, &cred)) >= 0) {
76 if (ret > 0) {
77 m_packetHandler(cred, data, ret);
78 }
79 if (m_stopServer.load()) {
80 break;
81 }
82 }
83 #endif
84 }
85 } // namespace HiviewDFX
86 } // namespace OHOS
87