Java Program terminates after JNI method call

对着背影说爱祢 提交于 2019-12-12 04:49:12

问题


I'm using JNI to call native C methods, but my java program terminates (Exit code 0) after the first method call and doesn't reach the rest of the code.

Here is my source:

Exec.java:

package libs;

public class Exec {

    static {
        System.load(System.getProperty("user.dir")+"/bin/"+"libexec.so");
    }

    public static native int execv(String pExecPath, String[] pArgs);
}

Exec.c:

#include <jni.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>


JNIEXPORT jint JNICALL
Java_libs_Exec_execv(JNIEnv * env, jclass clazz, jstring pExecPath, jobjectArray array) {
const char* execPath = (*env)->GetStringUTFChars(env, pExecPath, NULL); 
(*env)->ReleaseStringUTFChars(env, pExecPath, NULL);

printf("Execution path: %s\n", execPath);

int stringCount = (int) (*env)->GetArrayLength(env, array);
char * args[stringCount+1];
args[stringCount] = NULL;

for (int i=0; i<stringCount; i++) {
    jstring string = (jstring) (*env)->GetObjectArrayElement(env, array, i);
    char * arg = (*env)->GetStringUTFChars(env, string, 0);

    printf("Argument %i:\t%s\n", (i+1), arg);

    args[i] = arg;

    (*env)->ReleaseStringUTFChars(env, string, 0);
}



int result = execv(execPath, args);

printf("Exit code: %i\n", result);
perror(NULL);

return result;
}

TestExec.java:

package test;

import libs.Exec;


public class TestExec extends Exec {

    public static void main(String[] args) {

        execv("/bin/ps", new String[]{"ps", "ax"});
        execv("/bin/ls", new String[]{"ls", "-la", "/home"});
}
}

Console output:

PID TTY      STAT   TIME COMMAND
1 ?        Ss     0:00 /sbin/init
[...]
5532 ?        R      0:00 ps ax

I'm also missing the console output from my c-method, which should look like this:

Execution path: /bin/ps
Argument 1: ax
Exit code: 0

I hope I gave enough information to get qualified help.


回答1:


Of course it terminates. You're calling execv(). You're replacing the JVM with the 'ps' program, which exits, so you're done.

You can't call ReleaseStringUTFChars() while you're still holding a pointer to the chars.

And you won't see any output from a process after calling 'execv()', unless there was an error.

Are you sure you want to do this?



来源:https://stackoverflow.com/questions/23851048/java-program-terminates-after-jni-method-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!