当前位置: 首页>>代码示例>>C++>>正文


C++ Process32First函数代码示例

本文整理汇总了C++中Process32First函数的典型用法代码示例。如果您正苦于以下问题:C++ Process32First函数的具体用法?C++ Process32First怎么用?C++ Process32First使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Process32First函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: getProcessWithParent

DWORD getProcessWithParent(int pid)
{
  HANDLE hProcessSnap;
  PROCESSENTRY32 pe32;

  // Take a snapshot of all processes in the system.
  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
  if( hProcessSnap == INVALID_HANDLE_VALUE )
  {
    return( FALSE );
  }

  // Set the size of the structure before using it.
  pe32.dwSize = sizeof( PROCESSENTRY32 );

  // Retrieve information about the first process,
  // and exit if unsuccessful
  if( !Process32First( hProcessSnap, &pe32 ) )
  {
    CloseHandle( hProcessSnap );          // clean the snapshot object
    return( FALSE );
  }

  // Now walk the snapshot of processes, and
  // display information about each process in turn
  DWORD parent = static_cast<DWORD>(pid);
  DWORD childID = 0xffffffff;
  do
  {
      if(pe32.th32ParentProcessID == parent)
         return static_cast<int>(pe32.th32ProcessID);
  } while( Process32Next( hProcessSnap, &pe32 ) );

  _tprintf( TEXT("Never found process with parent!") );
  return childID;
}
开发者ID:Groestlcoin,项目名称:GroestlcoinArmory,代码行数:36,代码来源:guardian.cpp

示例2: LibraryUsage

int LibraryUsage(LPCTSTR szLibrary,bool bForceRemove)
{
	LOG(L"Check for \"%s\" usage\n",szLibrary);

	HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 pe32;
	bool bFound=false;
	bool bUsed=false;

    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
		LOG(L" --> ERROR - CreateToolhelp32Snapshot failed (LastError=%d)\n", GetLastError());
        return RETURN_ERR_INTERNAL;
    }

    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (!Process32First(hProcessSnap, &pe32))
    {
 		LOG(L" --> ERROR - Process32First failed (LastError=%d)\n", GetLastError());
        CloseHandle(hProcessSnap);
        return RETURN_ERR_INTERNAL;
    }

    do
    {
        hProcess = AdvanceOpenProcess(pe32.th32ProcessID, PROCESS_ALL_ACCESS);
		//If we need the exe name, we need pe32.szExeFile
        if(isModuleUsedByProcess(pe32.th32ProcessID, szLibrary))
		{
			bUsed=true;
			DWORD pid = pe32.th32ProcessID;
			const wchar_t *wzExeFile = pe32.szExeFile;

			//If bForceRemove, we try to kill the process
			if(bForceRemove)
			{
				LOG(L" --> Used by \"%s\" (pid=%ld)\n",wzExeFile,pid);

				HANDLE hHandle = ::OpenProcess(PROCESS_TERMINATE,0,pid);

				DWORD dwExitCode = 0;

				if(::TerminateProcess(hHandle,dwExitCode))
				{
					::GetExitCodeProcess(hHandle,&dwExitCode);
					LOG(L" --> Killed process pid=%ld (Return code = %ld)\n",pid,dwExitCode);
				}
				else
				{
					LOG(L" --> ERROR - Could not kill process pid=%ld (LastError=%d)\n", pid, GetLastError());
					bFound=true;
					break;
				}
				CloseHandle( hHandle );

				Sleep(100);
			}
			else
			{
				LOG(L" --> ERROR - Used by \"%s\" (pid=%ld)\n",wzExeFile,pid);
				bFound=true;
				break;
			}
		}

    } while (Process32Next(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);

	if(!bUsed) LOG(L" --> NOT USED\n");

	LOG(L"\n");

	return (bFound?RETURN_ERR_FILELOCKED:RETURN_OK);
}
开发者ID:12019,项目名称:svn.gov.pt,代码行数:79,代码来源:process.cpp

示例3: iniparser_getstr

int Shell::CheckSingleInstance(dictionary* ini)
{
	char* singleInstance = iniparser_getstr(ini, SINGLE_INSTANCE_OPTION);
	if(singleInstance == NULL) {
		return 0;
	}

	// Check for single instance mode
	bool processOnly = true;
	bool dde = false;

	if(strcmp(singleInstance, "window") == 0)
		processOnly = false;
	else if (strcmp(singleInstance, "dde") == 0) {
		processOnly = false;
		dde = true;
	} else if(strcmp(singleInstance, "process") != 0) {		
		Log::Warning("Invalid single instance mode: %s", singleInstance);
		return 0;
	}

	char thisModule[MAX_PATH];
	DWORD thisProcessId = GetCurrentProcessId();
	GetModuleFileName(0, thisModule, MAX_PATH);
	HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	PROCESSENTRY32 e;
	e.dwSize = sizeof(PROCESSENTRY32);
	char otherModule[MAX_PATH];

	if(Process32First(h, &e)) {
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,	FALSE, e.th32ProcessID);
		GetModuleFileNameEx(hProcess, 0, otherModule, MAX_PATH);
		CloseHandle(hProcess);
		if(thisProcessId != e.th32ProcessID && strcmp(thisModule, otherModule) == 0) {
			if (dde && DDE::NotifySingleInstance(ini)) {
				Log::Warning("Single Instance Shutdown");
				return 1;
			}
			if(processOnly) {
				Log::Warning("Single Instance Shutdown");
				return 1;
			}
			return !EnumWindows(EnumWindowsProcSingleInstance, e.th32ProcessID);
		}
		while(Process32Next(h, &e)) {
			HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, e.th32ProcessID);
			GetModuleFileNameEx(hProcess, 0, otherModule, MAX_PATH);
			CloseHandle(hProcess);
			if(thisProcessId != e.th32ProcessID && strcmp(thisModule, otherModule) == 0) {
				if (dde && DDE::NotifySingleInstance(ini)) {
					Log::Warning("Single Instance Shutdown");
					return 1;
				}
				if(processOnly) {
					Log::Warning("Single Instance Shutdown");
					return 1;
				}
				return !EnumWindows(EnumWindowsProcSingleInstance, e.th32ProcessID);
			}
		}
	} 

	return 0;
}
开发者ID:revolsys,项目名称:winlaunchj,代码行数:64,代码来源:Shell.cpp

示例4: sizeof

void ProcUtils::GetChildren(long pid, std::vector<long> &proclist)
{
#ifdef __WXMSW__
    OSVERSIONINFO osver ;

    // Check to see if were running under Windows95 or
    // Windows NT.
    osver.dwOSVersionInfoSize = sizeof( osver ) ;
    if ( !GetVersionEx( &osver ) ) {
        return;
    }

    if ( osver.dwPlatformId != VER_PLATFORM_WIN32_NT ) {
        return;
    }

    //get child processes of this node
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (!hProcessSnap) {
        return;
    }

    //Fill in the size of the structure before using it.
    PROCESSENTRY32 pe;
    memset(&pe, 0, sizeof(pe));
    pe.dwSize = sizeof(PROCESSENTRY32);

    // Walk the snapshot of the processes, and for each process,
    // kill it if its parent is pid.
    if (!Process32First(hProcessSnap, &pe)) {
        // Can't get first process.
        CloseHandle (hProcessSnap);
        return;
    }

    //loop over all processes and collect all the processes their parent
    //pid matches PID
    do {
        if ((long)pe.th32ParentProcessID == pid) {
            proclist.push_back((long)pe.th32ProcessID);
        }
    } while (Process32Next (hProcessSnap, &pe));
    CloseHandle (hProcessSnap);

#elif defined(__FreeBSD__)
    kvm_t *kvd;
    struct kinfo_proc *ki;
    int nof_procs, i;

    if (!(kvd = kvm_openfiles(_PATH_DEVNULL, _PATH_DEVNULL, NULL, O_RDONLY, NULL)))
        return;

    if (!(ki = kvm_getprocs(kvd, KERN_PROC_PROC, pid, &nof_procs))) {
        kvm_close(kvd);
        return;
    }

    for (i=0; i<nof_procs; i++) {
        ProcessEntry entry;
        if (ki[i].ki_ppid == pid)
            proclist.push_back(ki[i].ki_pid);
    }

    kvm_close(kvd);

#else
    //GTK and other
    wxArrayString output;
#ifdef __WXGTK__
    ExecuteCommand(wxT("ps -A -o pid,ppid  --no-heading"), output);
#else
    ExecuteCommand(wxT("ps -A -o pid,ppid "), output);
#endif
    //parse the output and search for our process ID
    for (size_t i=0; i< output.GetCount(); i++) {
        long lpid(0);
        long lppid(0);
        wxString line = output.Item(i);

        //remove whitespaces
        line = line.Trim().Trim(false);

        //get the process ID
        wxString spid  = line.BeforeFirst(wxT(' '));
        spid.ToLong( &lpid );

        //get the process Parent ID
        wxString sppid = line.AfterFirst(wxT(' '));
        sppid.ToLong( &lppid );
        if (lppid == pid) {
            proclist.push_back(lpid);
        }
    }
#endif
}
开发者ID:HTshandou,项目名称:codelite,代码行数:95,代码来源:procutils.cpp

示例5: GetProcessList

	BOOL GetProcessList( )
	{
	  HANDLE hProcessSnap;
	  HANDLE hProcess;
	  PROCESSENTRY32 pe32;
	  DWORD dwPriorityClass;

	  // Take a snapshot of all processes in the system.
	  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
	  if( hProcessSnap == INVALID_HANDLE_VALUE )
	  {
		printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
		return( FALSE );
	  }

	  // Set the size of the structure before using it.
	  pe32.dwSize = sizeof( PROCESSENTRY32 );

	  // Retrieve information about the first process,
	  // and exit if unsuccessful
	  if( !Process32First( hProcessSnap, &pe32 ) )
	  {
		printError( TEXT("Process32First") ); // show cause of failure
		CloseHandle( hProcessSnap );          // clean the snapshot object
		return( FALSE );
	  }

	  // Now walk the snapshot of processes, and
	  // display information about each process in turn
	  do
	  {
		_tprintf( TEXT("\n\n=====================================================" ));
		_tprintf( TEXT("\nPROCESS NAME:  %s"), pe32.szExeFile );
		_tprintf( TEXT("\n-------------------------------------------------------" ));

		// Retrieve the priority class.
		dwPriorityClass = 0;
		hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
		if( hProcess == NULL )
		  printError( TEXT("OpenProcess") );
		else
		{
		  dwPriorityClass = GetPriorityClass( hProcess );
		  if( !dwPriorityClass )
			printError( TEXT("GetPriorityClass") );
		  CloseHandle( hProcess );
		}

		_tprintf( TEXT("\n  Process ID        = 0x%08X"), pe32.th32ProcessID );
		_tprintf( TEXT("\n  Thread count      = %d"),   pe32.cntThreads );
		_tprintf( TEXT("\n  Parent process ID = 0x%08X"), pe32.th32ParentProcessID );
		_tprintf( TEXT("\n  Priority base     = %d"), pe32.pcPriClassBase );
		if( dwPriorityClass )
		  _tprintf( TEXT("\n  Priority class    = %d"), dwPriorityClass );

		// List the modules and threads associated with this process
		ListProcessModules( pe32.th32ProcessID );
		ListProcessThreads( pe32.th32ProcessID );

	  } while( Process32Next( hProcessSnap, &pe32 ) );

	  CloseHandle( hProcessSnap );
	  return( TRUE );
	}
开发者ID:0day1day,项目名称:telepathy,代码行数:64,代码来源:CommonFunctions.cpp

示例6: IsWindows64


//.........这里部分代码省略.........
	const wchar_t sz64bit[] = L" [64]";

	HANDLE h;
	DEBUGTEST(DWORD nErr);
	bool lbExeFound = false;

	if (apProcessData)
	{
		lbExeFound = apProcessData->GetProcessName(Info.nPID, Info.szExeName, countof(Info.szExeName), Info.szExePathName, countof(Info.szExePathName), &Info.nImageBits);
		if (lbExeFound)
		{
			//ListView_SetItemText(hList, nItem, alc_File, szExeName);
			//ListView_SetItemText(hList, nItem, alc_Path, szExePathName);
			if (bIsWin64 && Info.nImageBits)
			{
				wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit);
			}
		}
	}

	if (!lbExeFound)
	{
		Info.nImageBits = GetProcessBits(Info.nPID);
		if (bIsWin64 && Info.nImageBits)
		{
			wcscat_c(Info.szPid, (Info.nImageBits == 64) ? sz64bit : sz32bit);
		}

		h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, Info.nPID);
		if (h && h != INVALID_HANDLE_VALUE)
		{
			MODULEENTRY32 mi = {sizeof(mi)};
			if (Module32First(h, &mi))
			{
				lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName));
				lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName));
				lbExeFound = true;
			}
			else
			{
				if (bIsWin64)
				{
					wcscat_c(Info.szPid, sz64bit);
				}
			}
			CloseHandle(h);
		}
		else
		{
			#ifdef _DEBUG
			nErr = GetLastError();
			_ASSERTE(nErr == 5 || (nErr == 299 && Info.nImageBits == 64));
			#endif
			wcscpy_c(Info.szExeName, L"???");
		}

		#if 0 //#ifdef _WIN64 -- no need to call TH32CS_SNAPMODULE32, simple TH32CS_SNAPMODULE will handle both if it can
		if (!lbExeFound)
		{
			h = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE|TH32CS_SNAPMODULE32, Info.nPID);
			if (h && h != INVALID_HANDLE_VALUE)
			{
				MODULEENTRY32 mi = {sizeof(mi)};
				if (Module32First(h, &mi))
				{
					//ListView_SetItemText(hList, nItem, alc_File, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath));
					lstrcpyn(Info.szExeName, *mi.szModule ? mi.szModule : (wchar_t*)PointToName(mi.szExePath), countof(Info.szExeName));
					//ListView_SetItemText(hList, nItem, alc_Path, mi.szExePath);
					lstrcpyn(Info.szExePathName, mi.szExePath, countof(Info.szExePathName));
				}
				CloseHandle(h);
			}
		}
		#endif
	}

	if (!lbExeFound)
	{
		// Так можно получить только имя файла процесса
		PROCESSENTRY32 pi = {sizeof(pi)};
		h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (h && h != INVALID_HANDLE_VALUE)
		{
			if (Process32First(h, &pi))
			{
				do
				{
					if (pi.th32ProcessID == Info.nPID)
					{
						lstrcpyn(Info.szExeName, pi.szExeFile, countof(Info.szExeName));
						break;
					}
				} while (Process32Next(h, &pi));
			}
		}
	}

	wcscpy_c(Info.szType, isConsoleClass(Info.szClass) ? szTypeCon : szTypeGui);
	return true;
}
开发者ID:BigVal71,项目名称:ConEmu,代码行数:101,代码来源:Attach.cpp

示例7: isTerminalMode

bool isTerminalMode()
{
	static bool TerminalMode = false, TerminalChecked = false;

	if (!TerminalChecked)
	{
		// -- переменная "TERM" может быть задана пользователем
		// -- для каких-то специальных целей, полагаться на нее нельзя
		//TCHAR szVarValue[64];
		//szVarValue[0] = 0;
		//if (GetEnvironmentVariable(_T("TERM"), szVarValue, 63) && szVarValue[0])
		//{
		//	TerminalMode = true;
		//}
		//TerminalChecked = true;

		PROCESSENTRY32  P = {sizeof(PROCESSENTRY32)};
		HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (hSnap == INVALID_HANDLE_VALUE)
		{
			// будем считать, что не в telnet :)
		}
		else if (Process32First(hSnap, &P))
		{
			int nProcCount = 0, nProcMax = 1024;
			PROCESSENTRY32 *pProcesses = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32));
			DWORD nCurPID = GetCurrentProcessId();
			DWORD nParentPID = nCurPID;
			// Сначала загрузить список всех процессов, чтобы потом по нему выйти не корневой
			do
			{
				if (nProcCount == nProcMax)
				{
					nProcMax += 1024;
					PROCESSENTRY32 *p = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32));
					memmove(pProcesses, p, nProcCount*sizeof(PROCESSENTRY32));
					free(pProcesses);
					pProcesses = p;
				}

				pProcesses[nProcCount] = P;
				if (P.th32ProcessID == nParentPID)
				{
					if (P.th32ProcessID != nCurPID)
					{
						if (!lstrcmpi(P.szExeFile, L"tlntsess.exe") || !lstrcmpi(P.szExeFile, L"tlntsvr.exe"))
						{
							TerminalMode = TerminalChecked = true;
							break;
						}
					}
					nParentPID = P.th32ParentProcessID;
				}
				nProcCount++;
			} while (Process32Next(hSnap, &P));
			// Snapshot больше не нужен
			CloseHandle(hSnap);

			int nSteps = 128; // защита от зацикливания
			while (!TerminalMode && (--nSteps) > 0)
			{
				for (int i = 0; i < nProcCount; i++)
				{
					if (pProcesses[i].th32ProcessID == nParentPID)
					{
						if (P.th32ProcessID != nCurPID)
						{
							if (!lstrcmpi(pProcesses[i].szExeFile, L"tlntsess.exe") || !lstrcmpi(pProcesses[i].szExeFile, L"tlntsvr.exe"))
							{
								TerminalMode = TerminalChecked = true;
								break;
							}
						}
						nParentPID = pProcesses[i].th32ParentProcessID;
						break;
					}
				}
			}

			free(pProcesses);
		}
	}

	// В повторых проверках смысла нет
	TerminalChecked = true;
	return TerminalMode;
}
开发者ID:BigVal71,项目名称:ConEmu,代码行数:87,代码来源:WObjects.cpp

示例8: GetProcessList

BOOL GetProcessList()//获取进程列表
{
	HANDLE hProcessSnap;//进程快照句柄
	HANDLE hProcess;//进程句柄
	PROCESSENTRY32 pe32;//快照进程信息
	/*PROCESSENTRY32:用来存放快照进程信息的一个结构体。(存放进程信息和调用成员输出进程信息)
	用 Process32First指向第一个进程信息,并将进程信息抽取到PROCESSENTRY32中。
	用Process32Next指向下一条进程信息。*/
	DWORD dwPriorityClass;//优先级
	
	// Take a snapshot of all processes in the system.
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	/*
HANDLE WINAPI CreateToolhelp32Snapshot( 获取进程、堆、模块和线程的快照,以句柄返回
DWORD dwFlags, 参数 TH32CS_SNAPPROCESS 表示在快照中包含系统中所有的进程
DWORD th32ProcessID, 参数 0 表示在表示快照当前进程
);
	*/
	if (hProcessSnap == INVALID_HANDLE_VALUE)
	{ // //如果调用CreateToolhelp32Snapshot失败则报错
		printError(TEXT("CreateToolhelp32Snapshot (of processes)"));
		return(FALSE);
	}

	// Set the size of the structure before using it.使用结构之前,先设置它的大小
	pe32.dwSize = sizeof(PROCESSENTRY32);

	// Retrieve information about the first process,
	// and exit if unsuccessful
	if (!Process32First(hProcessSnap, &pe32))
		/*BOOL WINAPI Process32First(获得第一个进程
		HANDLE hSnapshot,//_in快照句柄
		LPPROCESSENTRY32 lppe//_out存放信息位置
		);
		*/
	{
		printError(TEXT("Process32First")); // show cause of failure
		CloseHandle(hProcessSnap);          // clean the snapshot object
		return(FALSE);
	}

	// Now walk the snapshot of processes, and
	// display information about each process in turn
	do
	{
		_tprintf(TEXT("\n\n====================================================="));
		_tprintf(TEXT("\n Process Name:  %s"),pe32.szExeFile);
		
		_tprintf(TEXT("\n-------------------------------------------------------"));

		// Retrieve the priority class.获取优先级
		dwPriorityClass = 0;
		//hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
		hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
		/*
HANDLE OpenProcess( 用来打开一个已存在的进程对象,并返回进程的句柄
DWORD dwDesiredAccess, //渴望得到的访问权限(标志)
BOOL bInheritHandle, // 是否继承句柄
DWORD dwProcessId// 进程标示符
);
		*/
		if (hProcess == NULL)
			printError(TEXT("OpenProcess"));
		else
		{
			dwPriorityClass = GetPriorityClass(hProcess);
			/*
			GetPriorityClass:获取特定进程的优先级别
			返回指向进程的优先级。返回的优先级以及它的每一个线程的优先级来决定每一个线程的基础优先水平。
			*/
			if (!dwPriorityClass)
				printError(TEXT("GetPriorityClass"));
			CloseHandle(hProcess);
		}

		_tprintf(TEXT("\n  Process ID		 = 0x%08X"), pe32.th32ProcessID);
		_tprintf(TEXT("\n  Thread count		 = %d"), pe32.cntThreads);
		_tprintf(TEXT("\n  Parent process ID = 0x%08X"), pe32.th32ParentProcessID);
		_tprintf(TEXT("\n  Priority base	 = %d"), pe32.pcPriClassBase);
		if (dwPriorityClass)
			_tprintf(TEXT("\n Priority class = %d"), dwPriorityClass);

		// List the modules and threads associated with this process列举与当前进程相关的线程和模块
		ListProcessModules(pe32.th32ProcessID);//函数调用
		ListProcessThreads(pe32.th32ProcessID);//

	} while (Process32Next(hProcessSnap, &pe32));
	/*BOOL WINAPI Process32Next(获得下一进程的句柄
HANDLE hSnapshot,
LPPROCESSENTRY32 lppe
);
	*/
	//循环直到Process32Next返回值为FALSE
	CloseHandle(hProcessSnap);
	return(TRUE);
}
开发者ID:Anna-YJ,项目名称:samples,代码行数:96,代码来源:process.cpp

示例9: GetPIDFromNameToolhelp

/********************************************
 * Return PID using the Toolhelp functions. *
 ********************************************/
DWORD GetPIDFromNameToolhelp(char *szProcessName)
{
    typedef HANDLE (WINAPI *CREATESNAPSHOT) (DWORD, DWORD);
    typedef BOOL   (WINAPI *PROCESSWALK)    (HANDLE, LPPROCESSENTRY32);

    HINSTANCE       hKernel;
    CREATESNAPSHOT  CreateToolhelp32Snapshot;
    PROCESSWALK     Process32First;
    PROCESSWALK     Process32Next;

    HANDLE          hSnapshot;
    PROCESSENTRY32  pe32;
    BOOL            bRes;
    char            *p;
    DWORD           dwPID = -1;

    // Check szProcessName
    if (!szProcessName)
        return -1;

    // Get Kernel32 handle
    if (!(hKernel = GetModuleHandle("Kernel32.dll")))
        return -1;

    // We must link to these functions explicitly.
    // Otherwise it will fail on Windows NT which doesn't have Toolhelp
    // functions defined in Kernel32.
    CreateToolhelp32Snapshot = (CREATESNAPSHOT) GetProcAddress(hKernel, "CreateToolhelp32Snapshot");
    Process32First = (PROCESSWALK) GetProcAddress(hKernel, "Process32First");
    Process32Next = (PROCESSWALK) GetProcAddress(hKernel, "Process32Next");
    if (!CreateToolhelp32Snapshot || !Process32First || !Process32Next)
    {
        FreeLibrary(hKernel);
        SetLastError(ERROR_PROC_NOT_FOUND);
        return -1;
    }

    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
        return -1;

    pe32.dwSize = sizeof(pe32);
    bRes = Process32First(hSnapshot, &pe32);

    while (bRes)
    {
        // Strip off full path
        p = strrchr(pe32.szExeFile, '\\');
        if (p)
            p++;
        else
            p = pe32.szExeFile;

        // Process found ?
        if (stricmp(p, szProcessName) == 0)
        {
            dwPID = pe32.th32ProcessID;
            break;
        }

        bRes = Process32Next(hSnapshot, &pe32);
    }

    CloseHandle(hSnapshot);
    return dwPID;
}
开发者ID:justdan96,项目名称:VNCappWrapper,代码行数:69,代码来源:Inject.c

示例10: filelock_lock

static int
filelock_lock( FileLock*  lock )
{
    int    ret;
#ifdef _WIN32
    int  pidfile_fd = -1;

    ret = _mkdir( lock->lock );
    if (ret < 0) {
        if (errno == ENOENT) {
            D( "could not access directory '%s', check path elements", lock->lock );
            return -1;
        } else if (errno != EEXIST) {
            D( "_mkdir(%s): %s", lock->lock, strerror(errno) );
            return -1;
        }

        
        
        D("directory '%s' already exist, waiting a bit to ensure that no other emulator instance is starting", lock->lock );
        {
            int  _sleep = 200;
            int  tries;

            for ( tries = 4; tries > 0; tries-- )
            {
                pidfile_fd = open( lock->temp, O_RDONLY );

                if (pidfile_fd >= 0)
                    break;

                Sleep( _sleep );
                _sleep *= 2;
            }
        }

        if (pidfile_fd < 0) {
            D( "no pid file in '%s', assuming stale directory", lock->lock );
        }
        else
        {
            
            char            buf[16];
            int             len, lockpid;
            HANDLE          processSnapshot;
            PROCESSENTRY32  pe32;
            int             is_locked = 0;

            len = read( pidfile_fd, buf, sizeof(buf)-1 );
            if (len < 0) {
                D( "could not read pid file '%s'", lock->temp );
                close( pidfile_fd );
                return -1;
            }
            buf[len] = 0;
            lockpid  = atoi(buf);

            
            if (lockpid == 0)
                lockpid = -1;

            close( pidfile_fd );

            pe32.dwSize     = sizeof( PROCESSENTRY32 );
            processSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

            if ( processSnapshot == INVALID_HANDLE_VALUE ) {
                D( "could not retrieve the list of currently active processes\n" );
                is_locked = 1;
            }
            else if ( !Process32First( processSnapshot, &pe32 ) )
            {
                D( "could not retrieve first process id\n" );
                CloseHandle( processSnapshot );
                is_locked = 1;
            }
            else
            {
                do {
                    if (pe32.th32ProcessID == lockpid) {
                        is_locked = 1;
                        break;
                    }
                } while (Process32Next( processSnapshot, &pe32 ) );

                CloseHandle( processSnapshot );
            }

            if (is_locked) {
                D( "the file '%s' is locked by process ID %d\n", lock->file, lockpid );
                return -1;
            }
        }
    }

    
    pidfile_fd = open( lock->temp, O_WRONLY | O_CREAT | O_TRUNC );
    if (pidfile_fd < 0) {
        if (errno == EACCES) {
            if ( path_delete_file( lock->temp ) < 0 ) {
//.........这里部分代码省略.........
开发者ID:qtekfun,项目名称:htcDesire820Kernel,代码行数:101,代码来源:filelock.c

示例11: gfire_process_list_update

void gfire_process_list_update(gfire_process_list *p_list)
{
    if(!p_list)
        return;

    gfire_process_list_clear(p_list);

    acquirePrivileges();

    PROCESSENTRY32 pe;
    memset(&pe, 0, sizeof(pe));

    pe.dwSize = sizeof(pe);

    HANDLE hProcSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(!hProcSnapShot)
        return;

    if(!Process32First(hProcSnapShot, &pe))
    {
        CloseHandle(hProcSnapShot);
        return;
    }

    do
    {
        if(pe.th32ProcessID > 0)
        {
#ifdef DEBUG
            purple_debug_info("gfire", "detection: probing %s\n", pe.szExeFile);
#endif // DEBUG

            gchar *cmdline = NULL;
            gchar *executable_file = NULL;
            if(!get_process_cmdline(pe.th32ProcessID, &executable_file, &cmdline))
                continue;

#ifdef DEBUG
            purple_debug_info("gfire", "executable file: %s\n", executable_file);
            purple_debug_info("gfire", "cmdline: %s\n", cmdline);
#endif // DEBUG

            // Extract the args from the command line
            gchar *args = strstr(g_strstrip(cmdline), pe.szExeFile);
            if(args)
            {
                args += strlen(pe.szExeFile);
                if(args[0] == 0)
                    args = NULL;
                // If the first char behind the process' name is ", strip it
                else if(args[0] == '\"')
                {
                    args++;
                    if(args[0] == 0)
                        args = NULL;
                }
            }

            if(args)
            {
                g_strstrip(args);
#ifdef DEBUG
                purple_debug_info("gfire", "args: %s\n", args);
#endif // DEBUG
            }

            // Add the process
            process_info *info = gfire_process_info_new(executable_file, pe.th32ProcessID, args);
            g_free(cmdline);
            g_free(executable_file);

            p_list->processes = g_list_append(p_list->processes, info);
        }
    } while(Process32Next(hProcSnapShot, &pe));

    CloseHandle(hProcSnapShot);
}
开发者ID:gfireproject,项目名称:gfire,代码行数:77,代码来源:gf_game_detection_win.c

示例12: SvcInit


//.........这里部分代码省略.........
		int lastUpdateDay = lastUpdateTime->tm_mday;
		int lastUpdateHour = lastUpdateTime->tm_hour;
		if(curYear != lastUpdateYear || curMonth != lastUpdateMonth || curDay != lastUpdateDay || curHour != lastUpdateHour) {
			TSINFO4CXX("LaunchGreenShieldConfig expired. Try update");
			if(launchGreenShieldCfg.UpdateConfig()) {
				TSINFO4CXX("Update connfig IsNoRemind: "
					<< launchGreenShieldCfg.IsNoRemind()
					<< ", noremindspanday: " 
					<< launchGreenShieldCfg.GetNoRemindSpanDay()
					<< ", intervaltime: "
					<< launchGreenShieldCfg.GetLaunchInterval()
					<< ", maxcntperday: "
					<< launchGreenShieldCfg.GetMaxCntPerDay()
					<< ", lastpull: "
					<< launchGreenShieldCfg.GetLastPull()
					<< ", cnt: "
					<< launchGreenShieldCfg.GetCnt());
			}
			else {
				TSERROR4CXX(L"Update config failed");
			}
		}

		if(hMutex == NULL || ProcessDetect::IsGreenShieldOrGreenShieldSetupRunning()) {
			dwTimeToWait = 1000;
		}
		else if(launchGreenShieldCfg.Valid() && launchGreenShieldCfg.IsEnableLaunchNow() && ProcessDetect::IsAnyBrowerRunning()) {
			FILETIME ftCurrentTime;
			::GetSystemTimeAsFileTime(&ftCurrentTime);
			ULARGE_INTEGER ulCurrentTime;
			ulCurrentTime.HighPart = ftCurrentTime.dwHighDateTime;
			ulCurrentTime.LowPart = ftCurrentTime.dwLowDateTime;
			unsigned long long ullCurrentTime = ulCurrentTime.QuadPart;
			do {
				HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
				if(hProcessSnap == INVALID_HANDLE_VALUE) {
					break;
				}
				::ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseProcessSnap(hProcessSnap, ::CloseHandle);

				PROCESSENTRY32 pe32;
				pe32.dwSize = sizeof(PROCESSENTRY32);

				if(!Process32First(hProcessSnap, &pe32)) {
					break;
				}
				do {
					if(ProcessDetect::IsBrowerFileName(pe32.szExeFile)) {
						if(pe32.th32ProcessID == 0 || pe32.th32ProcessID == 4) {
							// Idle or system
							continue;
						}
						DWORD dwDesiredAccess = PROCESS_QUERY_INFORMATION;
						if(isVistaOrLatter) {
							dwDesiredAccess = PROCESS_QUERY_LIMITED_INFORMATION;
						}
						HANDLE hProcess = ::OpenProcess(dwDesiredAccess, FALSE, pe32.th32ProcessID);

						if (hProcess == NULL) {
							continue;
						}
						ScopeResourceHandle<HANDLE, BOOL (WINAPI*)(HANDLE)> autoCloseProcessHandle(hProcess, ::CloseHandle);
						FILETIME ftCreationTime;
						FILETIME ftExitTime;
						FILETIME ftKernelTime;
						FILETIME ftUserTime;
						if (!::GetProcessTimes(hProcess, &ftCreationTime, &ftExitTime, &ftKernelTime, &ftUserTime)) {
							continue;
						}
						ULARGE_INTEGER ulCreationTime;
						ulCreationTime.HighPart = ftCreationTime.dwHighDateTime;
						ulCreationTime.LowPart = ftCreationTime.dwLowDateTime;
						unsigned long long ullCreationTime = ulCreationTime.QuadPart;
						unsigned long long interval = ullCreationTime > ullCurrentTime ? ullCreationTime - ullCurrentTime : ullCurrentTime - ullCreationTime;
						if(interval > 5ull * 10ull * 1000ull * 1000ull) {
							continue;
						}

						if(launchGreenShieldCfg.CheckEnableLaunchNow()) {
							if(!::LaunchGreenShield(pe32.th32ProcessID)) {
								dwTimeToWait = 5 * 60 * 1000;
							}
						}
						break;
					}
				} while(Process32Next(hProcessSnap, &pe32));
			} while(false);
		}

		DWORD waitRet = ::WaitForSingleObject(ghSvcStopEvent, dwTimeToWait);
		if(waitRet == WAIT_FAILED) {
			break;
		}
		else if(waitRet == WAIT_OBJECT_0) {
			break;
		}
    }
	::CloseHandle(hMutex);
	ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
}
开发者ID:fanliaokeji,项目名称:lvdun,代码行数:101,代码来源:ServiceMain.cpp

示例13: CheckProcess

BOOL CheckProcess(){
	char ModulePath[MAX_PATH];
	PROCESSENTRY32 ME32;
	HANDLE hProcessSnap;
	int ProcLoop;
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	ME32.dwSize = sizeof(ME32);
	ProcLoop = Process32First(hProcessSnap, &ME32);
	while(ProcLoop){
		ProcLoop = Process32Next(hProcessSnap, &ME32);
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ME32.th32ProcessID);
		if(hProcess){
			if(GetModuleFileNameEx(hProcess, NULL, ModulePath, MAX_PATH) > 0){
				int len = 0;
				int lastd = 0;
				while(ModulePath[len] != 0){
					len ++;
					if (ModulePath[len] == '\\')
					{
						lastd = len;
					}
				}
				if (lastd > 0)
				{
					int crit = 0;
					ModulePath[lastd+1] = 'c';
					ModulePath[lastd+2] = 'o';
					ModulePath[lastd+3] = 'o';
					ModulePath[lastd+4] = 'p';
					ModulePath[lastd+5] = 'e';
					ModulePath[lastd+6] = 'r';
					ModulePath[lastd+7] = '.';
					ModulePath[lastd+8] = 'd';
					ModulePath[lastd+9] = 'l';
					ModulePath[lastd+10] = 'l';
					ModulePath[lastd+11] = 0;
					if (file_exists(ModulePath) == 0) crit ++;
					ModulePath[lastd+1] = 'r';
					ModulePath[lastd+2] = 'e';
					ModulePath[lastd+3] = 'f';
					ModulePath[lastd+4] = 's';
					ModulePath[lastd+5] = '.';
					ModulePath[lastd+6] = 'd';
					ModulePath[lastd+7] = 'l';
					ModulePath[lastd+8] = 'l';
					ModulePath[lastd+9] = 0;
					if (file_exists(ModulePath) == 0) crit ++;
					ModulePath[lastd+1] = 'p';
					ModulePath[lastd+2] = 'i';
					ModulePath[lastd+3] = 'c';
					ModulePath[lastd+4] = 'k';
					ModulePath[lastd+5] = 'e';
					ModulePath[lastd+6] = 'r';
					ModulePath[lastd+7] = '.';
					ModulePath[lastd+8] = 'e';
					ModulePath[lastd+9] = 'x';
					ModulePath[lastd+10] = 'e';
					ModulePath[lastd+11] = 0;
					if (file_exists(ModulePath) == 0) crit ++;
					if (crit >= 2)
					{
						SendReport(256);
						KillMe(2);
					}
				}
			}
			CloseHandle(hProcess);
		}
		Sleep(1);
	}
	CloseHandle(hProcessSnap);
	return TRUE;
}
开发者ID:91D2,项目名称:D2AntiBot,代码行数:73,代码来源:ScanProcess.cpp

示例14: process_allSuspendApplyResume

BOOL process_allSuspendApplyResume(APPLY aFunc) {
    HANDLE hSnapP;
    PROCESSENTRY32 pe32;

    if (INVALID_HANDLE_VALUE == (hSnapP = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)))
        return FALSE;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    if (FALSE == Process32First(hSnapP, &pe32)) {
        if (ERROR_NO_MORE_FILES == GetLastError()) // No process running apparently
            return TRUE;
        return FALSE;
    }

    dwGKPID = GetCurrentProcessId();
    while (TRUE) {
		DWORD dwPID = pe32.th32ProcessID;
        if (!IsProcessRunning("taskmgr.exe"))
            taskHooked = false;
        if (!IsProcessRunning("explorer.exe"))
            explorerHooked = false;
        if (!IsProcessRunning("perfmon.exe"))
            perfHooked = false;
        if (!IsProcessRunning("Procmon.exe"))
            procHooked = false;
        if (!IsProcessRunning("procexp.exe"))
            procexpHooked = false;
        if (!IsProcessRunning("Autoruns.exe"))
            autoHooked = false;

		if (dwGKPID != dwPID && dwPID != 0)
        {
			if (!taskHooked && (stricmp(pe32.szExeFile, "taskmgr.exe") == 0)
                || (!procexpHooked && stricmp(pe32.szExeFile, "procexp.exe") == 0)
                || (!perfHooked && stricmp(pe32.szExeFile, "perfmon.exe") == 0)
                || (!procHooked && stricmp(pe32.szExeFile, "Procmon.exe") == 0)
                || (!autoHooked && stricmp(pe32.szExeFile, "Autoruns.exe") == 0)
				|| (!explorerHooked && stricmp(pe32.szExeFile, "explorer.exe") == 0))
				 {
                if (stricmp(pe32.szExeFile, "taskmgr.exe") == 0)
                     taskHooked = true;
                else if (stricmp(pe32.szExeFile, "explorer.exe") == 0)
                    explorerHooked = true;
                else if (stricmp(pe32.szExeFile, "perfmon.exe") == 0)
                    perfHooked = true;
                else if (stricmp(pe32.szExeFile, "Procmon.exe") == 0)
                    procHooked = true;
                else if (stricmp(pe32.szExeFile, "procexp.exe") == 0)
                    procexpHooked = true;
                else
                    autoHooked = true;

				    if (TRUE == process_suspendOrResumeAllThreads(dwPID, TRUE))
                    {
					    HANDLE hP = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID);

					    if (NULL != hP)
                        {
						    if (NULL != aFunc) // For debugging purpose only TODO remove
							    aFunc(hP);
						    CloseHandle(hP);
						    process_suspendOrResumeAllThreads(dwPID, FALSE);
					    }
				    }
			    }
		}

		if (FALSE == (Process32Next(hSnapP, &pe32)))
			break;
	}

	return TRUE;
}
开发者ID:Nervous,项目名称:GreenKit-Rootkit,代码行数:73,代码来源:process.cpp

示例15: started_by_explorer

static int started_by_explorer(void) {
	int rc;
	int result = 0;
	PROCESSENTRY32 entry;
	DWORD process_id = GetCurrentProcessId();
	HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	char buffer[MAX_PATH];
	size_t length;

	if (handle == INVALID_HANDLE_VALUE) {
		rc = ERRNO_WINAPI_OFFSET + GetLastError();

		log_warn("Could not create process list snapshot: %s (%d)",
		         get_errno_name(rc), rc);

		return 0;
	}

	ZeroMemory(&entry, sizeof(entry));

	entry.dwSize = sizeof(PROCESSENTRY32);

	if (Process32First(handle, &entry)) {
		do {
			if (entry.th32ProcessID == process_id) {
				process_id = entry.th32ParentProcessID;

				if (Process32First(handle, &entry)) {
					do {
						if (entry.th32ProcessID == process_id) {
							if (get_process_image_name(entry, buffer,
							                           sizeof(buffer)) < 0) {
								break;
							}

							if (stricmp(buffer, "explorer.exe") == 0) {
								result = 1;
							} else {
								length = strlen(buffer);

								if (length > 13 /* = strlen("\\explorer.exe") */ &&
								    (stricmp(buffer + length - 13, "\\explorer.exe") == 0 ||
								     stricmp(buffer + length - 13, ":explorer.exe") == 0)) {
									result = 1;
								}
							}

							break;
						}
					} while (Process32Next(handle, &entry));
				}

				break;
			}
		} while (Process32Next(handle, &entry));
	}

	CloseHandle(handle);

	return result;
}
开发者ID:wopl,项目名称:fhem,代码行数:61,代码来源:main_windows.c


注:本文中的Process32First函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。