+ Reply to Thread
Results 1 to 1 of 1

Thread: How to terminate process in C++

  1. #1

    How to terminate process in C++

    This functions will terminate all processes by name that match process name passed to pkill. This code does not work under NT 4.0.
    Code:
     
    int KillProc(char *pkill)
     {
     
       HANDLE hProcess, hSnapshot;
       PROCESSENTRY32 ProcessEntry;
       BOOL moreproc = FALSE;
       int count = 1, fail = 0;
       char *pname;
     
      hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
      
       if(hSnapshot == (HANDLE)-1)
          return 1;
     
     ProcessEntry.dwSize = sizeof(ProcessEntry);                   // we need to set the size to work
      moreproc = Process32First(hSnapshot, &ProcessEntry); 
      
      while(moreproc)      // if success it returns true
      {
         
        hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessEntry.th32ProcessID);
     
       if(hProcess == NULL)
        {
         moreproc = Process32Next(hSnapshot, &ProcessEntry);
         continue;
        }
        
          _strlwr(pkill);                                // lowercase the string
           _strlwr(ProcessEntry.szExeFile);
         
         
           pname = strrchr(ProcessEntry.szExeFile, '\\');   // we do this cause under NT system it is only process name but in 9x it is full path 
       if(pname == NULL)
              pname = ProcessEntry.szExeFile;  
        else
           pname++;   
       
       if(!(strcmp(pkill, pname))) 
       {
          if(TerminateProcess(hProcess, 0xffffffff))     // kill process
             cout <<"\nProcess " << "\"" << pname << "\"" << " (" << count << ") " << " was terminated."; 
        else fail++;
           
          count++; 
       } 
         
        
        CloseHandle(hProcess);
           moreproc = Process32Next(hSnapshot, &ProcessEntry);
      
      
      }  // end while
     
      if(fail)
        return 1;
       else 
       return 0;  // success
     
    }
    Last edited by David; 12-28-2011 at 10:57 PM.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts