我正在使用JNI调用本机C方法,但是我的java程序在第一个方法调用后终止(退出代码0),并且没有到达其余代码.
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.
这是我的出处:
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:
#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"}); } }控制台输出:
PID TTY STAT TIME COMMAND 1 ? Ss 0:00 /sbin/init [...] 5532 ? R 0:00 ps ax我还缺少我的c方法的控制台输出,该输出看起来应该像这样:
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.
推荐答案当然终止.您正在调用execv().您将用"ps"程序替换JVM,该程序将退出,从而完成操作.
Of course it terminates. You're calling execv(). You're replacing the JVM with the 'ps' program, which exits, so you're done.
当您仍然持有指向chars的指针时,无法调用ReleaseStringUTFChars().
You can't call ReleaseStringUTFChars() while you're still holding a pointer to the chars.
除非有错误,否则调用'execv()'后您将看不到进程的任何输出.
And you won't see any output from a process after calling 'execv()', unless there was an error.
确定要执行此操作吗?
更多推荐
Java程序在JNI方法调用后终止
发布评论