RSS FEED

22 oct 2010

Cerrar proceso sin necesidad de PID

Código con el podemos cerrar un proceso sin tener que preocuparnos por saber el PID del proceso que deseamos cerrar.



#include <windows.h>
#include <winbase.h>
#include <tlhelp32.h>
#include <ctype.h>
#include <string.h>

//P4|3L0


int matarproceso(const char *szToTerminate)
{

    BOOL endtask = false;
    BOOL bResult,bResultm;
    DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
    DWORD iCbneeded,i;
    char szName[MAX_PATH],szToTermUpper[MAX_PATH];
    HANDLE hProc,hSnapShot,hSnapShotm;
    HINSTANCE hInstLib;
    int iLen,iLenP,indx;
    HMODULE hMod;
    PROCESSENTRY32 procentry;      
    MODULEENTRY32 modentry;
    iLenP=strlen(szToTerminate);
    for(indx=0;indx<iLenP;indx++)
    szToTermUpper[indx]=toupper(szToTerminate[indx]);
    szToTermUpper[iLenP]=0;
    BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
    BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,DWORD, LPDWORD );
    DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,LPTSTR, DWORD );
    HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD);
    BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32);
    BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32);
    BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32);
    BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32);
    hInstLib = LoadLibraryA("PSAPI.DLL");
    lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))GetProcAddress( hInstLib, "EnumProcesses" );
    lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,DWORD, LPDWORD)) GetProcAddress( hInstLib,"EnumProcessModules" );
    lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE, LPTSTR, DWORD )) GetProcAddress( hInstLib,"GetModuleBaseNameA" );
    bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
    iNumProc=iCbneeded/sizeof(DWORD);
    for(i=0;i<iNumProc;i++){
    strcpy(szName,"¿?");
    hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,aiPID[i]);
    if(hProc){
    if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) ){
    iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);}}
    CloseHandle(hProc);
    #ifdef BORLANDC
                if(strcmp(strupr(szName),szToTermUpper)==0)
    #else
                if(strcmp(_strupr(szName),szToTermUpper)==0)
    #endif

                {hProc=OpenProcess(PROCESS_TERMINATE,FALSE,aiPID[i]);
    if(hProc)
    {
        (TerminateProcess(hProc,1));
        endtask = true;
    }
    }
    }
    if(endtask) return(1);
    return(0);
}
int main(void)
{
matarproceso("notepad.exe");
return 0;
}

No hay comentarios:

Publicar un comentario

Arriba