2012-02-17 68 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