简体   繁体   中英

Java Program terminates after JNI method call

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM