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