VOID AppDrone() { ULONG i, j; HANDLE outp; CHAR outstring[80]; outp = CreateFile('s'); RtlFormatString(outstring, 80, "\r\nDrone with PID:%d started\r\n", GetProcessId()); WriteString(outp, outstring); KdPrint("in drone 1"); //Sleep(DRONE_SLEEP_TIME); KdPrint("in drone after sleep"); RtlFormatString(outstring, 80, "\r\nDrone with PID:%d still alive\r\n", GetProcessId()); for (i = 0; i < 3; i++) { KdPrint("in drone 2"); WriteString(outp, outstring); for(j=0;j<0xFFFFFF;j++); //Sleep(DRONE_SLEEP_TIME); } RtlFormatString(outstring, 80, "\r\nDrone with PID:%d killing my self\r\n", GetProcessId()); KdPrint("in drone 3"); WriteString(outp, outstring); CloseHandle(outp); KillMe(); }
DWORD CALLBACK CaptureAndSuspendProcess(LPVOID) { ImpersonateAnonymousToken(GetCurrentThread()); while (NtGetNextProcess(nullptr, MAXIMUM_ALLOWED, 0, 0, &g_hProcess) != 0) { } NTSTATUS status = NtSuspendProcess(g_hProcess); printf("Suspended process: %08X %p %d\n", status, g_hProcess, GetProcessId(g_hProcess)); RevertToSelf(); SetProcessId(GetProcessId(g_hProcess)); WCHAR cmdline[] = L"notepad.exe"; STARTUPINFO startInfo = {}; PROCESS_INFORMATION procInfo = {}; startInfo.cb = sizeof(startInfo); if (CreateProcessWithLogonW(L"user", L"domain", L"password", LOGON_NETCREDENTIALS_ONLY, nullptr, cmdline, CREATE_SUSPENDED, nullptr, nullptr, &startInfo, &procInfo)) { printf("Created process %d\n", procInfo.dwProcessId); } else { printf("Create error: %d\n", GetLastError()); } TerminateProcess(g_hProcess, 0); ExitProcess(0); return 0; }
void FProcState::Wait() { if (bHasBeenWaitedFor) { return; // we could try waitpid() another time, but why } for(;;) // infinite loop in case we get EINTR and have to repeat { siginfo_t SignalInfo; if (waitid(P_PID, GetProcessId(), &SignalInfo, WEXITED)) { if (errno != EINTR) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("FLinuxPlatformProcess::WaitForProc: waitid for pid %d failed (errno=%d, %s)"), static_cast< int32 >(GetProcessId()), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo))); break; // exit the loop if for some reason Fatal log (above) returns } } else { check(SignalInfo.si_pid == GetProcessId()); ReturnCode = (SignalInfo.si_code == CLD_EXITED) ? SignalInfo.si_status : -1; bHasBeenWaitedFor = true; bIsRunning = false; // set in advance break; } } }
static void MyCreateProcessCommon(BOOL bRet, DWORD dwCreationFlags, LPPROCESS_INFORMATION lpProcessInformation) { if (!bRet) { debugPrintf("inject: warning: failed to create child process\n"); return; } DWORD dwLastError = GetLastError(); if (isDifferentArch(lpProcessInformation->hProcess)) { debugPrintf("inject: error: child process %lu has different architecture\n", GetProcessId(lpProcessInformation->hProcess)); } else { char szDllPath[MAX_PATH]; GetModuleFileNameA(g_hThisModule, szDllPath, sizeof szDllPath); if (!injectDll(lpProcessInformation->hProcess, szDllPath)) { debugPrintf("inject: warning: failed to inject into child process %lu\n", GetProcessId(lpProcessInformation->hProcess)); } } if (!(dwCreationFlags & CREATE_SUSPENDED)) { ResumeThread(lpProcessInformation->hThread); } SetLastError(dwLastError); }
DWORD PsProcessHandleToId(HANDLE ProcessHandle) { HANDLE targetHandle; DWORD processId; if (ProcessHandle == GetCurrentProcess()) { return GetCurrentProcessId(); } processId = GetProcessId(ProcessHandle); if (processId) { return processId; } if (!PsCopyHandle(GetCurrentProcess(), ProcessHandle, &targetHandle, PROCESS_QUERY_INFORMATION, FALSE)) { return 0; } processId = GetProcessId(targetHandle); CloseHandle(targetHandle); return processId; }
int main(int argc, char* argv[]) { int a = fork(); char *env[] = {"PATH=C:\\TEST", NULL}; if(a > 0) { printf("\nParent ProcessID : %d\n",GetProcessId()); waitpid(a); printf("\nAfter Child Process has exited"); sleep(10); printf("\nParent : After Sleep"); } else { printf("\nChild ProcessID : %d\n",GetProcessId()); char *inp[] = {"bin/hello","a","b"}; execvpe(inp[0],inp,env); } return 0; }
bool FProcState::IsRunning() { if (bIsRunning) { check(!bHasBeenWaitedFor); // check for the sake of internal consistency // check if actually running int KillResult = kill(GetProcessId(), 0); // no actual signal is sent check(KillResult != -1 || errno != EINVAL); bIsRunning = (KillResult == 0 || (KillResult == -1 && errno == EPERM)); // additional check if it's a zombie if (bIsRunning) { for(;;) // infinite loop in case we get EINTR and have to repeat { siginfo_t SignalInfo; SignalInfo.si_pid = 0; // if remains 0, treat as child was not waitable (i.e. was running) if (waitid(P_PID, GetProcessId(), &SignalInfo, WEXITED | WNOHANG | WNOWAIT)) { if (errno != EINTR) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("FLinuxPlatformProcess::WaitForProc: waitid for pid %d failed (errno=%d, %s)"), static_cast< int32 >(GetProcessId()), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo))); break; // exit the loop if for some reason Fatal log (above) returns } } else { bIsRunning = ( SignalInfo.si_pid != GetProcessId() ); break; } } } // If child is a zombie, wait() immediately to free up kernel resources. Higher level code // (e.g. shader compiling manager) can hold on to handle of no longer running process for longer, // which is a dubious, but valid behavior. We don't want to keep zombie around though. if (!bIsRunning) { UE_LOG(LogHAL, Log, TEXT("Child %d is no more running (zombie), Wait()ing immediately."), GetProcessId() ); Wait(); } } return bIsRunning; }
void Log(char* szFormat, ...) { va_list vaArgs; va_start(vaArgs, szFormat); int len = _vscprintf(szFormat, vaArgs); char* szString = new char[len+1]; vsprintf_s(szString, len+1, szFormat, vaArgs); va_end(vaArgs); time_t tTime; time(&tTime); char szTime[128] = ""; struct tm time; localtime_s(&time, &tTime); strftime(szTime, sizeof(szTime), "%x %X", &time); char path[_MAX_PATH+_MAX_FNAME] = ""; sprintf_s(path, sizeof(path), "%sd2bs.log", Vars.szPath); #ifdef DEBUG FILE* log = stderr; #else FILE* log = _fsopen(path, "a+", _SH_DENYNO); #endif fprintf(log, "[%s] D2BS %d: %s\n", szTime, GetProcessId(GetCurrentProcess()), szString); #ifndef DEBUG fflush(log); fclose(log); #endif delete[] szString; }
BOOL MEMINFO_API C_GetProcMemInfo(_In_ DWORD dwProcId, _Out_ PPROCMEMINFO_C pProcMemInfo){ HANDLE hProc = NULL; MEMORYSTATUSEX status; PROCESS_MEMORY_COUNTERS procMemCtr; printf("\n\n~~~~ INFORMACAO LOCAL DO PROCESSO ~~~~~"); status.dwLength = sizeof (status); if (hProc = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, FALSE, dwProcId) == NULL || !GlobalMemoryStatusEx(&status) || !GetProcessMemoryInfo(hProc, &procMemCtr, sizeof(PROCESS_MEMORY_COUNTERS))){ printf("ERROR: %s\n", GetLastError()); return FALSE; } printf("\nProcess ID = %u", GetProcessId(hProc)); printf("\nTotal de espaco de enderecamento virtual existente: %llu KiB = %llu MiB", status.ullTotalVirtual / KiloB, status.ullTotalVirtual / MegaB); printf("\nTotal de espaco de enderecamento virtual disponivel: %llu KiB = %llu MiB", status.ullAvailVirtual / KiloB, status.ullAvailVirtual / MegaB); printf("\nDimensao do Working Set: %u KiB = %.2f MiB", procMemCtr.WorkingSetSize / KiloB, (double)procMemCtr.WorkingSetSize / MegaB); // Afectar a struct _out_ pProcMemInfo->processId = dwProcId; pProcMemInfo->workingSetSize = procMemCtr.WorkingSetSize; pProcMemInfo->totalVirtualSpace = status.ullTotalVirtual; pProcMemInfo->availableVirtualSpace = status.ullAvailVirtual; printf("\n\nClique em qualquer tecla para terminar..."); getchar(); CloseHandle(hProc); return TRUE; }
int KProcess::getProcessId() { #ifdef _WIN32 return GetProcessId(pid); #else return pid; #endif }
int fork(void) { RTL_USER_PROCESS_INFORMATION info; NTSTATUS result; if (w32_fork == NULL) return -ENOSYS; /* lets do this */ result = w32_fork(RTL_CLONE_FLAGS, NULL, NULL, NULL, &info); if (result == CLONE_PARENT) { pid_t pid = GetProcessId(info.Process); ResumeThread(info.Thread); CloseHandle(info.Process); CloseHandle(info.Thread); return pid; } else if (result == CLONE_CHILD) { /* fix stdio */ AllocConsole(); return 0; } else return -1; return -1; }
void CdbDumperHelper::moduleLoadHook(const QString &module, HANDLE debuggeeHandle) { if (loadDebug > 1) qDebug() << "moduleLoadHook" << module << m_state << debuggeeHandle; switch (m_state) { case Disabled: case Initialized: break; case NotLoaded: // Try an inject load as soon as a Qt lib is loaded. // for the thread to finish as this would lock up. if (m_tryInjectLoad && module.contains(QLatin1String("Qt"), Qt::CaseInsensitive)) { // Also shows up in the log window. m_manager->showStatusMessage(msgLoading(m_library, true), messageTimeOut); QString errorMessage; SharedLibraryInjector sh(GetProcessId(debuggeeHandle)); if (sh.remoteInject(m_library, false, &errorMessage)) { m_state = InjectLoading; } else { m_state = InjectLoadFailed; // Ok, try call loading... m_manager->showDebuggerOutput(LogMisc, msgLoadFailed(m_library, true, errorMessage)); } } break; case InjectLoading: // check if gdbmacros.dll loaded if (module.contains(QLatin1String(dumperModuleNameC), Qt::CaseInsensitive)) { m_state = Loaded; m_manager->showDebuggerOutput(LogMisc, msgLoadSucceeded(m_library, true)); } break; } }
int evalProcesses(HANDLE hProcess) { if (NULL == hProcess) return 0; unsigned int totalMemUsage = 0; DWORD processID = GetProcessId(hProcess); HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 processEntry = { 0 }; processEntry.dwSize = sizeof(PROCESSENTRY32); // Retrieves information about the first process encountered in a system snapshot if(Process32First(hProcessSnapshot, &processEntry)) { do { // if th32processID = processID, we are the parent process! // if th32ParentProcessID = processID, we are a child process! if ((processEntry.th32ProcessID == processID) || (processEntry.th32ParentProcessID == processID)) { unsigned int procMemUsage = 0; // Record parent process memory procMemUsage = getMemoryInfo(processEntry.th32ProcessID); totalMemUsage += procMemUsage; } // Retrieves information about the next process recorded in a system snapshot. } while(Process32Next(hProcessSnapshot, &processEntry)); } CloseHandle(hProcessSnapshot); return totalMemUsage; }
bool Application_ClientConfigManager::closeProcess(DWORD processId, DWORD* error) { HANDLE hProcess = OpenProcess(PROCESS_TERMINATE,TRUE, processId); if(hProcess == NULL) { *error = GetLastError(); if(*error == ERROR_INVALID_PARAMETER) { *error = CAPTURE_PE_PROCESS_ALREADY_TERMINATED; } } else { EnumWindows(Application_ClientConfigManager::EnumWindowsProc, (LPARAM)processId); DWORD tempProcessId = GetProcessId(hProcess); if(tempProcessId == processId) { if(!TerminateProcess(hProcess, 0)) { *error = GetLastError(); } else { *error = CAPTURE_PE_PROCESS_TERMINATED_FORCEFULLY; } } else { return true; } } return false; }
BOOL AppIsAlreadyRunning() { BOOL bRunning=FALSE; CString strAppName; strAppName = "ZuneNowPlaying.exe"; DWORD dwOwnPID = GetProcessId(GetCurrentProcess()); HANDLE hSnapShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); PROCESSENTRY32* processInfo=new PROCESSENTRY32; processInfo->dwSize=sizeof(PROCESSENTRY32); int index=0; while(Process32Next(hSnapShot,processInfo)!=FALSE) { CString pName = (LPCWSTR)processInfo->szExeFile; if (pName.CompareNoCase(strAppName) == 0) { if (processInfo->th32ProcessID != dwOwnPID) { bRunning=TRUE; break; } } } CloseHandle(hSnapShot); delete processInfo; return bRunning; }
Bool restoreBackandParams( void* self, BackendParams param) { strcpy(DataDir, param->dataDir, MAX_PATH); memcpy(ListenSockets, ¶m->listenSockets, sizeof(socket_type)); CancelKey = param->cancelKey; ChildSlot = param->childSlot; ProcId = GetProcessId(GetCurrentProcess()); StartTime = param->startTime; ReloadTime = param->reloadTime; LoggerFileTime = param->loggerFileTime; RedirectDone = param->redirectDone; maxFileDescriptors = param->maxSafeFileDescriptors; memcpy(&logPipe, ¶m->logPipe, sizeof(logPipe)); strcpy(ExecPath, param->execPath); return True; }
DWORD JpfsvGetProcessIdContext( __in JPFSV_HANDLE ContextHandle ) { PJPFSV_CONTEXT Context = ( PJPFSV_CONTEXT ) ContextHandle; ASSERT( Context && Context->Signature == JPFSV_CONTEXT_SIGNATURE ); if ( Context && Context->Signature == JPFSV_CONTEXT_SIGNATURE ) { if ( Context->ProcessHandle == JPFSV_KERNEL_PSEUDO_HANDLE ) { // // Kernel context. // return JPFSV_KERNEL; } else { return GetProcessId( Context->ProcessHandle ); } } else { return 0; } }
bool TerminateIfRunning ( void ) { bool bAlreadyRunning = false; unsigned int index = 0; DWORD dwOwnPID = GetProcessId ( GetCurrentProcess () ); HANDLE hSnapShot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 ); PROCESSENTRY32* processInfo = new PROCESSENTRY32; processInfo->dwSize = sizeof ( PROCESSENTRY32 ); while ( Process32Next ( hSnapShot, processInfo ) != 0 ) { // Convert WCHAR to const char * const char * strFileName = reinterpret_cast < const char * >( processInfo->szExeFile ); if ( !strcmp ( strFileName, "_TODO_EXE_NAME_.exe" ) ) { if ( processInfo->th32ProcessID != dwOwnPID ) { bAlreadyRunning = true; break; } } } CloseHandle ( hSnapShot ); delete processInfo; return bAlreadyRunning; }
void log_init_thread() { if (!logger_attached) return; LPCWSTR pipeName = L"\\\\.\\pipe\\flog_server"; for (;;) { hLoggerPipe = CreateFileW(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hLoggerPipe == INVALID_HANDLE_VALUE) { /* Non critical error code, just wait and try connecting again */ if (GetLastError() != ERROR_PIPE_BUSY || !WaitNamedPipeW(pipeName, NMPWAIT_WAIT_FOREVER)) { logger_attached = 0; break; } continue; } /* Send initial request */ struct request request; request.magic = PROTOCOL_MAGIC; request.version = PROTOCOL_VERSION; request.pid = GetProcessId(GetCurrentProcess()); request.tid = GetThreadId(GetCurrentThread()); DWORD written; if (!WriteFile(hLoggerPipe, &request, sizeof(request), &written, NULL)) { CloseHandle(hLoggerPipe); logger_attached = 0; } break; } }
void KillProcessByNameExcludingMyself(LPCTSTR lpName) { HANDLE hCurrentProcess; DWORD dwCurrentProcess; HANDLE hSnapShot; PROCESSENTRY32 pEntry; BOOL hRes; HANDLE hProcess; hCurrentProcess = GetCurrentProcess(); dwCurrentProcess = GetProcessId(hCurrentProcess); hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0); pEntry.dwSize = sizeof(pEntry); hRes = Process32First(hSnapShot, &pEntry); while (hRes) { if (strcmp(pEntry.szExeFile, lpName) == 0 && pEntry.th32ProcessID != dwCurrentProcess) { hProcess = OpenProcess(PROCESS_TERMINATE, 0, (DWORD) pEntry.th32ProcessID); if (hProcess != NULL) { TerminateProcess(hProcess, 9); CloseHandle(hProcess); } } hRes = Process32Next(hSnapShot, &pEntry); } CloseHandle(hSnapShot); }
//---------------------------- int main(int argc, char* argv[]) { // Declare our dll variable char dll[MAX_PATH]; if ( argc != 3 ) { cout << "Usage :" << argv[0] << " <PROCESS NAME> <DLL FULL PATH>" << endl; exit(1); } // Get the full path of our .dll GetFullPathName( argv[2] , MAX_PATH, dll , NULL); // Get PID of notepad.exe DWORD ID = GetProcessId(argv[1]); if (!CreateRemoteThreadInject(ID, dll)) { //If CreateRemoteThreadInject Returned true cout << "Injection failed!" << endl ; exit(1); } else { //If CreateRemoteThreadInject Returned true cout << "Injection of" << argv[2] << " into " << argv[1] << " is successful!" << endl; exit(1); } return 0; }
/* Unload Dll from process RETURN: Error code */ DWORD CMemDll::Unload() { HANDLE hThread = NULL; HMODULE hDll = NULL; if(!CMemCore::Instance().m_hProcess) return ERROR_INVALID_HANDLE; //Search for dll in process if((hDll = (HMODULE)GetModuleAddress(GetProcessId(CMemCore::Instance().m_hProcess), TEXT(DLL_NAME))) !=0 ) { hThread = CreateRemoteThread ( CMemCore::Instance().m_hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "FreeLibrary"), (void*)hDll, 0, NULL ); if(hThread == NULL) { MessageBox(NULL, TEXT("Cannot create thread"), TEXT("Error"), MB_ICONERROR); return GetLastError(); } //Wait for completion WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); } return ERROR_SUCCESS; }
HMODULE GetRemoteModuleHandle( char *szModuleName, HANDLE hProcess, bool bUsePath ) { HANDLE tlh = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, GetProcessId( hProcess ) ); MODULEENTRY32 modEntry; modEntry.dwSize = sizeof( MODULEENTRY32 ); Module32First( tlh, &modEntry ); do { string comp; comp.clear(); if(bUsePath){ comp = modEntry.szExePath; } else { comp = modEntry.szModule; } if( !strcmp( szModuleName, comp.c_str() ) ) { CloseHandle( tlh ); return modEntry.hModule; } } while(Module32Next( tlh, &modEntry ) ); CloseHandle( tlh ); return NULL; }
void PauseResumeThreadList( bool bResumeThread ) { if (hProcess == NULL) return; DWORD dwOwnerPID = GetProcessId(hProcess); HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) return; THREADENTRY32 te32; ZeroMemory(&te32,sizeof(te32)); te32.dwSize = sizeof(THREADENTRY32); BOOL MoreThreads = Thread32First(hThreadSnap, &te32); while (MoreThreads) { if (te32.th32OwnerProcessID == dwOwnerPID) { HANDLE hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID); if (bResumeThread) ResumeThread(hThread); else SuspendThread(hThread); CloseHandle(hThread); } MoreThreads = Thread32Next(hThreadSnap, &te32); } CloseHandle (hThreadSnap); }
void srand2() { unsigned long seed = srand2_mix( clock(), (unsigned long)time(NULL), GetProcessId(GetModuleHandle(NULL))); srand(seed); }
unsigned long ClassSpaceChecker::runProgram(const QString &theUri, const QString ¶m, bool silentMode, bool waitExit) { QString uri = QDir::toNativeSeparators(theUri); std::wstring uriW = uri.toStdWString().c_str(); std::wstring paramW = param.toStdWString().c_str(); SHELLEXECUTEINFOW shellExInfo; memset(&shellExInfo, 0, sizeof(SHELLEXECUTEINFO)); shellExInfo.cbSize = sizeof(SHELLEXECUTEINFO); shellExInfo.hwnd = NULL; shellExInfo.lpVerb = L"open"; shellExInfo.lpFile = uriW.c_str(); shellExInfo.lpParameters = paramW.c_str(); shellExInfo.lpDirectory = NULL; shellExInfo.nShow = silentMode ? SW_HIDE : SW_SHOWNORMAL; shellExInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE; shellExInfo.hInstApp = NULL; ShellExecuteEx(&shellExInfo); if(waitExit) WaitForSingleObject(shellExInfo.hProcess,INFINITE); unsigned long processId = GetProcessId(shellExInfo.hProcess); return processId; }
ULONG currentProcessId(IDebugSystemObjects *sysObjects) { ULONG64 handle = 0; if (sysObjects->GetCurrentProcessHandle(&handle) == S_OK) return GetProcessId((HANDLE)handle); return 0; }
child::child( HANDLE h ):handle_(h),pid_(0) { pid_ = get_invalidate_pid(); if(handle_ != INVALID_HANDLE_VALUE) { pid_ = GetProcessId(handle_); } }
/** * There are a bunch of functions that you expect to return a pid, * like Unix.getpid() and Unix.create_process(). However, on * Windows, instead of returning the process ID, they return a * process handle. * * Process handles seem act like pointers to a process. You can have * more than one handle that points to a single process (unlike * pids, where there is a single pid for a process). * * This isn't a problem normally, since functons like Unix.waitpid() * will take the process handle on Windows. But if you want to print * or log the pid, then you need to dereference the handle and get * the pid. And that's what this function does. */ value pid_of_handle(value handle) { CAMLparam1(handle); #ifdef _WIN32 CAMLreturn(Val_int(GetProcessId((HANDLE)Long_val(handle)))); #else CAMLreturn(handle); #endif }
STDMETHODIMP CBProcess::get_ProcessID(LONG* newVal) { DWORD dwRet = GetProcessId(m_hProcess); if (!dwRet) return HRESULT_FROM_WIN32(GetLastError()); *newVal = (LONG)dwRet; return S_OK; }