ndktest

view src/logger.c @ 0:1310df7cdf25

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 23 Apr 2015 20:54:02 +0300
parents
children
line source
1 #include <stdio.h>
2 #include <assert.h>
3 #include <unistd.h>
4 #include <pthread.h>
5 #include <android/log.h>
6 #include "logger.h"
7 #include "app.h"
9 static void *thread_func(void *arg);
11 static int pfd[2];
12 static pthread_t thr;
13 static int initialized;
15 int start_logger(void)
16 {
17 if(initialized) {
18 return 1;
19 }
21 /* set stdout to line-buffered, and stderr to unbuffered */
22 setvbuf(stdout, 0, _IOLBF, 0);
23 setvbuf(stderr, 0, _IONBF, 0);
25 if(pipe(pfd) == -1) {
26 perror("failed to create logging pipe");
27 return -1;
28 }
29 assert(pfd[0] > 2 && pfd[1] > 2);
31 /* redirect stdout & stderr to the write-end of the pipe */
32 dup2(pfd[1], 1);
33 dup2(pfd[1], 2);
35 /* start the logging thread */
36 if(pthread_create(&thr, 0, thread_func, 0) == -1) {
37 perror("failed to spawn logging thread");
38 return -1;
39 }
40 pthread_detach(thr);
41 return 0;
42 }
44 static void *thread_func(void *arg)
45 {
46 ssize_t rdsz;
47 char buf[257];
49 __android_log_print(ANDROID_LOG_DEBUG, APP_NAME, "logger starting up...");
51 while((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) {
52 if(buf[rdsz - 1] == '\n') {
53 --rdsz;
54 }
55 buf[rdsz] = 0;
56 __android_log_write(ANDROID_LOG_DEBUG, APP_NAME, buf);
57 }
59 __android_log_print(ANDROID_LOG_DEBUG, APP_NAME, "logger shutting down...");
60 return 0;
61 }