22683891bd02d7d4d7979fb66358e4f6a84b50be
[platform/core/dotnet/launcher.git] / NativeLauncher / util / log_manager.cc
1 /*
2  * Copyright (c) 2016 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 <stdio.h>
18 #include <unistd.h>
19 #include <pthread.h>
20
21 #include "log.h"
22 #include "log_manager.h"
23
24 static int __pfd[2];
25 static pthread_t loggingThread;
26
27 static void *stdlog(void*)
28 {
29     ssize_t readSize;
30     char buf[1024];
31
32     while ((readSize = read(__pfd[0], buf, sizeof buf - 1)) > 0) {
33         if (buf[readSize - 1] == '\n') {
34             --readSize;
35         }
36
37         buf[readSize] = 0;
38
39         _LOGX("%s", buf);
40     }
41
42         close(__pfd[0]);
43         close(__pfd[1]);
44
45     return 0;
46 }
47
48 int initializeLogManager()
49 {
50     if (setvbuf(stdout, NULL, _IOLBF, 0) < 0) {
51                 _ERR("fail to make stdout line-buffered");
52                 return -1;
53     }
54
55     if (setvbuf(stderr, NULL, _IONBF, 0) < 0) {
56                 _ERR("make stderr unbuffered");
57                 return -1;
58         }
59
60     /* create the pipe and redirect stdout and stderr */
61     if (pipe(__pfd) < 0) {
62                 _ERR("fail to create pipe for logging");
63                 return -1;
64     }
65
66         return 0;
67 }
68
69 int redirectFD()
70 {
71         if (__pfd[1] < 0) {
72                 _ERR("fail to create pipe for logging");
73                 return -1;
74         }
75     // stdout
76     if (dup2(__pfd[1], 1) == -1) {
77                 _ERR("fail to duplicate fd to stdout");
78                 return -1;
79     }
80
81     // stderr
82     if (dup2(__pfd[1], 2) == -1) {
83                 _ERR("fail to duplicate fd to stderr");
84                 return-1;
85         }
86
87         return 0;
88 }
89
90 int runLoggingThread()
91 {
92     /* spawn the logging thread */
93     if (pthread_create(&loggingThread, 0, stdlog, 0) != 0) {
94                 _ERR("fail to create pthread");
95         return -1;
96     }
97
98     if (pthread_detach(loggingThread) != 0) {
99                 _ERR("fail to detach pthread");
100                 return -1;
101         }
102
103     return 0;
104 }
105