今天在使用OpenProcess函数的时候,偶然发现,如果某个pid能够打开,那么pid+1,pid+2,pid+3同样能打开,而且是同样的进程。打开任务管理器才发现进程的pid都是4的倍数,以前都没发现。
然后写了个简单的验证程序,结果很有意思。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <psapi.h>
int main()
{
DWORD pid;
HANDLE ph;
char name[MAX_PATH];
for (pid = 0; pid < 65535; pid++) {
ph = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (ph == NULL) {
continue;
}
memset(name, 0, sizeof(name));
if (0 != GetModuleBaseName(ph, NULL, name, sizeof(name))) {
printf("%6ld: %s\n", pid, name);
}
CloseHandle(ph);
}
return 0;
}
在我的机器上运行结果为:
1416: cmd.exe 1417: cmd.exe 1418: cmd.exe 1419: cmd.exe 1488: Explorer.EXE 1489: Explorer.EXE 1490: Explorer.EXE 1491: Explorer.EXE 1676: plugin-container.exe 1677: plugin-container.exe 1678: plugin-container.exe 1679: plugin-container.exe 1828: avastUI.exe 1829: avastUI.exe 1830: avastUI.exe 1831: avastUI.exe 1932: OpenProcessTest.exe 1933: OpenProcessTest.exe 1934: OpenProcessTest.exe 1935: OpenProcessTest.exe 1992: ctfmon.exe 1993: ctfmon.exe 1994: ctfmon.exe 1995: ctfmon.exe 2044: conime.exe 2045: conime.exe 2046: conime.exe 2047: conime.exe 2296: vmware.exe 2297: vmware.exe 2298: vmware.exe 2299: vmware.exe 2544: FirefoxPortable.exe 2545: FirefoxPortable.exe 2546: FirefoxPortable.exe 2547: FirefoxPortable.exe 2560: firefox.exe 2561: firefox.exe 2562: firefox.exe 2563: firefox.exe
现象就一目了然了。
Windows
引用来自“开源中国X科长”的评论
是某种程度的HASH算法 N是键的区间大小 便于机器定位进程编号,操作进程和树 很多公司 特别大公司的题目 都有HASH的影子 JDK里也有 比如你放一个字符串对象到HashSet里 HASH就用字符串的HASHCODE(Java里的伪地址) 那么你有10000万个元素的时候就不需要迭代一万次 只需要找到他的hashcode所在的区间 然后迭代区间元素 甚至递归hash 但是老外思想就是多,还有人用斐波拉契堆和素数表来设计比hash更为惊叹的算法