ndktest
diff 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 diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/logger.c Thu Apr 23 20:54:02 2015 +0300 1.3 @@ -0,0 +1,61 @@ 1.4 +#include <stdio.h> 1.5 +#include <assert.h> 1.6 +#include <unistd.h> 1.7 +#include <pthread.h> 1.8 +#include <android/log.h> 1.9 +#include "logger.h" 1.10 +#include "app.h" 1.11 + 1.12 +static void *thread_func(void *arg); 1.13 + 1.14 +static int pfd[2]; 1.15 +static pthread_t thr; 1.16 +static int initialized; 1.17 + 1.18 +int start_logger(void) 1.19 +{ 1.20 + if(initialized) { 1.21 + return 1; 1.22 + } 1.23 + 1.24 + /* set stdout to line-buffered, and stderr to unbuffered */ 1.25 + setvbuf(stdout, 0, _IOLBF, 0); 1.26 + setvbuf(stderr, 0, _IONBF, 0); 1.27 + 1.28 + if(pipe(pfd) == -1) { 1.29 + perror("failed to create logging pipe"); 1.30 + return -1; 1.31 + } 1.32 + assert(pfd[0] > 2 && pfd[1] > 2); 1.33 + 1.34 + /* redirect stdout & stderr to the write-end of the pipe */ 1.35 + dup2(pfd[1], 1); 1.36 + dup2(pfd[1], 2); 1.37 + 1.38 + /* start the logging thread */ 1.39 + if(pthread_create(&thr, 0, thread_func, 0) == -1) { 1.40 + perror("failed to spawn logging thread"); 1.41 + return -1; 1.42 + } 1.43 + pthread_detach(thr); 1.44 + return 0; 1.45 +} 1.46 + 1.47 +static void *thread_func(void *arg) 1.48 +{ 1.49 + ssize_t rdsz; 1.50 + char buf[257]; 1.51 + 1.52 + __android_log_print(ANDROID_LOG_DEBUG, APP_NAME, "logger starting up..."); 1.53 + 1.54 + while((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) { 1.55 + if(buf[rdsz - 1] == '\n') { 1.56 + --rdsz; 1.57 + } 1.58 + buf[rdsz] = 0; 1.59 + __android_log_write(ANDROID_LOG_DEBUG, APP_NAME, buf); 1.60 + } 1.61 + 1.62 + __android_log_print(ANDROID_LOG_DEBUG, APP_NAME, "logger shutting down..."); 1.63 + return 0; 1.64 +}