istereo2

annotate src/android/logger.c @ 23:7d795dade0bc

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