Modify CPUBoostingController
[platform/core/appfw/launchpad.git] / src / lib / launchpad-common / socket.cc
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the License);
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an AS IS BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "launchpad-common/socket.hh"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <unistd.h>
26
27 #include "launchpad-common/log_private.hh"
28
29 namespace launchpad {
30 namespace {
31
32 constexpr const int MAX_RETRY_CNT = 2;
33
34 }  // namespace
35
36 Socket::Socket(int fd) : fd_(fd) {}
37
38 Socket::~Socket() {
39   Close();
40 }
41
42 void Socket::Close() {
43   if (fd_ > -1) {
44     close(fd_);
45     fd_ = -1;
46   }
47 }
48
49 int Socket::Write(const void* buf, size_t size) {
50   const unsigned char* buffer = static_cast<const unsigned char*>(buf);
51   size_t left = size;
52
53   while (left) {
54     ssize_t bytes = write(fd_, buffer, left);
55     if (bytes < 0) {
56       int ret = -errno;
57       _E("Write() is failed. fd(%d), errno(%d)", fd_, errno);
58       return ret;
59     }
60
61     left -= bytes;
62     buffer += bytes;
63   }
64
65   return 0;
66 }
67
68 int Socket::Read(void* buf, size_t size) {
69   unsigned char* buffer = static_cast<unsigned char*>(buf);
70   size_t left = size;
71
72   while (left) {
73     ssize_t bytes = read(fd_, buffer, left);
74     if (bytes == 0) {
75       _W("EOF. fd(%d)", fd_);
76       return -EIO;
77     }
78
79     if (bytes < 0)
80       return -errno;
81
82     left -= bytes;
83     buffer += bytes;
84   }
85
86   return 0;
87 }
88
89 bool Socket::IsClosed() const {
90   return fd_ < 0;
91 }
92
93 int Socket::GetFd() const {
94   return fd_;
95 }
96
97 int Socket::RemoveFd() {
98   int fd = fd_;
99   fd_ = -1;
100   return fd;
101 }
102
103 }  // namespace launchpad