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