问题
Although it is fairly easy to do manually, I am attempting to automate the setting of cpu affinity in Windows 7 for various VMs after their initial creation time. The project is in Java and I am trying to avoid directly including C code, so I have been using Java Native Access, which masks things like winapi. I'm new to the library, and it's a bit lacking in tutorials or examples, although there are some basic ones findable through quick Google searches.
Using the following code, I can set the affinity of the main Java process (ffffffffffffffff locally), but other processes remain completely unaffected, even when I have the privileges to manually set affinity using Task Manager. I have also iterated over all integers from 0 to 10000, rather than just entering ids I know to be valid.
Main class:
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinNT.HANDLE;
public class SetAffinity {
public static void main(String[] args){
int pid = -1;
AffinityKernel instance = (AffinityKernel)Native.loadLibrary("Kernel32",AffinityKernel.class));
System.out.println(instance.SetProcessAffinityMask(new HANDLE(new Pointer(pid)), 1));
}
}
Utility interface:
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT.HANDLE;
public interface AffinityKernel extends Kernel32{
public boolean SetProcessAffinityMask(HANDLE hProcess, int dwProcessAffinityMask);
}
Since I can check that it correctly sets the cpu affinity of the process it's running in, I know the syntax is correct.
The question is:
How do I access/reference processes besides the current process?
回答1:
The other routine you're looking for is OpenProcess, which allows you to get a HANDLE to another process, which you can then use in the SetProcessAffinityMask
. The calling signature:
HANDLE OpenProcess(DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId);
It's exposed in the Kernel32 interface already.
Determining the process id of the other java processes using JNA has been asked already, and should be understandable.
来源:https://stackoverflow.com/questions/25211253/how-to-use-java-native-access-to-set-process-affinity-for-processes-besides-java