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.
我正在使用JNI来调用本机C方法,但是我的java程序在第一次方法调用之后终止(退出代码0)并且没有到达其余的代码。
Here is my source:
这是我的来源:
Exec.java:
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:
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:
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:
我也错过了我的c方法的控制台输出,它应该是这样的:
Execution path: /bin/ps
Argument 1: ax
Exit code: 0
I hope I gave enough information to get qualified help.
我希望我提供足够的信息以获得合格的帮助。
1 个解决方案
#1
1
Of course it terminates. You're calling execv(). You're replacing the JVM with the 'ps' program, which exits, so you're done.
当然它终止了。你正在调用execv()。您正在使用退出的'ps'程序替换JVM,所以您已经完成了。
You can't call ReleaseStringUTFChars() while you're still holding a pointer to the chars.
当你仍然持有指向字符的指针时,你不能调用ReleaseStringUTFChars()。
And you won't see any output from a process after calling 'execv()', unless there was an error.
除非出现错误,否则在调用'execv()'后,您将看不到进程的任何输出。
Are you sure you want to do this?
你确定你要这么做吗?
#1
1
Of course it terminates. You're calling execv(). You're replacing the JVM with the 'ps' program, which exits, so you're done.
当然它终止了。你正在调用execv()。您正在使用退出的'ps'程序替换JVM,所以您已经完成了。
You can't call ReleaseStringUTFChars() while you're still holding a pointer to the chars.
当你仍然持有指向字符的指针时,你不能调用ReleaseStringUTFChars()。
And you won't see any output from a process after calling 'execv()', unless there was an error.
除非出现错误,否则在调用'execv()'后,您将看不到进程的任何输出。
Are you sure you want to do this?
你确定你要这么做吗?