Capturing stdout/stderr with NDK

前端 未结 3 752
渐次进展
渐次进展 2020-12-09 04:57

I am porting some existing C code to run on Android. This C code writes lots of output to stdout/stderr. I need to capture this output, either in a memory buffer or a file,

3条回答
  •  离开以前
    2020-12-09 05:22

    Use something like this to redirect stderr to a pipe. Have a reader on the other side of the pipe write to logcat:

    extern "C" void Java_com_test_yourApp_yourJavaClass_nativePipeSTDERRToLogcat(JNIEnv* env, jclass cls, jobject obj)
    {
        int pipes[2];
        pipe(pipes);
        dup2(pipes[1], STDERR_FILENO);
        FILE *inputFile = fdopen(pipes[0], "r");
        char readBuffer[256];
        while (1) {
            fgets(readBuffer, sizeof(readBuffer), inputFile);
            __android_log_write(2, "stderr", readBuffer);
        }
    }
    

    You'll want to run this in its own thread. I spin up the thread in Java and then have the Java thread call this NDK code like this:

    new Thread() {
        public void run() {
            nativePipeSTDERRToLogcat();
        }
    }.start();
    

提交回复
热议问题