2012-02-17 72 views
1

当调用ExitWindowsEX Windows API函数时,我曾经有一些特权问题。C++代码正常工作,但在从Java(JNI)调用时不起作用

所以我写了下面的代码来获得特权:

这工作正常,在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

请您详细说明您的意思是“不起作用”吗?崩溃?从API调用返回的错误代码(哪个?)没有错误/崩溃但没有看到? – Flexo 2012-02-17 09:44:48

+0

'jlong​​'是64位的,我非常确定'int'在C中不会超过32位(不是它应该会导致你的问题) – 2012-02-17 09:50:57

+0

1.我的函数返回0,它意味着'GetLastError()'返回没有错误2.只要我知道我在类型转换中没有错误3.通过不起作用我的意思是'ExitWindowsEx'工作,因为它没有完整的特权(注销工程关闭并重新启动不起作用) – ehsun7b 2012-02-17 09:57:40

回答

0

有什么理由不使用System.exit(int)

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

+1

大概是因为WindowsExitEx用于不同的目的:它会关闭Windows或重新启动。 – 2013-05-09 12:14:41