C ++代码工作正常,但从Java(JNI)调用时不起作用

时间:2012-02-17 09:43:24

标签: java c++ java-native-interface

在调用ExitWindowsEX Windows API函数时,我曾经遇到过一些特权问题。

所以我编写了以下代码来获得权限:

这在C ++中运行良好

#include <cstdlib>
#include <windows.h>
#include <iostream>


using namespace std;

/*
 * 
 */

int MyExitWindows(int flag, int reason);

int main(int argc, char** argv) {
  MyExitWindows(EWX_SHUTDOWN, 0);
}

int MyExitWindows(int flag, int reason) {
  HANDLE hToken;
  TOKEN_PRIVILEGES tkp;

  //   Get   a   token   for   this   process.     

  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    return GetLastError();

  //   Get   the   LUID   for   the   shutdown   privilege.     

  LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

  tkp.PrivilegeCount = 1; //   one   privilege   to   set           
  tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

  //   Get   the   shutdown   privilege   for   this   process.     

  AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
          (PTOKEN_PRIVILEGES) NULL, 0);

  //   Cannot   test   the   return   value   of   AdjustTokenPrivileges.     

  ExitWindowsEx(flag, reason);
  if (GetLastError() != ERROR_SUCCESS) {
    return GetLastError();
  }

  return 0;
}

但是当我从Java中调用它时,这不起作用

#include <jni.h>
#include <cstdlib>
#include <windows.h>
#include "com_ehsunbehravesh_jshutdown_system_Shutdowner.h"

using namespace std;

int MyExitWindows(int flag, int reason);

JNIEXPORT jint JNICALL Java_com_ehsunbehravesh_jshutdown_system_Shutdowner_exitWindowsEx
(JNIEnv *env, jobject obj, jlong flag, jlong reason) {
  return MyExitWindows(flag, reason);
}

int MyExitWindows(int flag, int reason) {
  HANDLE hToken;
  TOKEN_PRIVILEGES tkp;

  //   Get   a   token   for   this   process.     

  int cpid = GetCurrentProcessId();
  printf("%d", cpid);
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    return GetLastError();

  //   Get   the   LUID   for   the   shutdown   privilege.     

  LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

  tkp.PrivilegeCount = 1; //   one   privilege   to   set           
  tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

  //   Get   the   shutdown   privilege   for   this   process.     

  AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
          (PTOKEN_PRIVILEGES) NULL, 0);

  //   Cannot   test   the   return   value   of   AdjustTokenPrivileges.     

  ExitWindowsEx(flag, reason);
  if (GetLastError() != ERROR_SUCCESS) {
    return GetLastError();
  }

  return 0;
}

1 个答案:

答案 0 :(得分:0)

你有没有理由不使用System.exit(int)

Java尝试控制应用程序的关闭,也许它试图阻止你以其他方式执行。