进程操作

来源:互联网 发布:java校招面经 编辑:程序博客网 时间:2024/06/06 16:31
Code:
  1. #include <windows.h>   
  2. #include <stdio.h>   
  3. #include <stdlib.h>   
  4. #include <string.h>   
  5. #include <tlhelp32.h>   
  6. int KillProcess(DWORD Pid)   
  7. {   
  8.     //打开进程得到进程句柄   
  9.     HANDLE hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,Pid);   
  10.     if(hProcess==NULL)   
  11.     {          
  12.         printf("OpenProcess error/n");   
  13.         return 0;   
  14.     }   
  15.     //结束进程   
  16.     if (TerminateProcess(hProcess,0))   
  17.     {   
  18.         printf("结束进程成功/n");   
  19.         return 0;   
  20.     }   
  21.     else  
  22.     {   
  23.         printf("结束进程失败/n");   
  24.         return 0;   
  25.     }      
  26. }   
  27.   
  28. int GetProcess()   
  29. {   
  30.     char buff[1024]={0};   
  31.     PROCESSENTRY32 pe32;   
  32.     pe32.dwSize=sizeof(pe32);   
  33.     //获得系统内所有进程快照   
  34.     HANDLE hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);   
  35.     if(hProcessSnap==INVALID_HANDLE_VALUE)   
  36.     {   
  37.         printf("CreateToolhelp32Snapshot error");   
  38.         return 0;   
  39.     }   
  40.     //枚举列表中的第一个进程   
  41.     BOOL bProcess=Process32First(hProcessSnap,&pe32);   
  42.     while(bProcess)   
  43.     {   
  44.         //格式化进程名和进程ID   
  45.         wsprintf(buff,"%s---------------%d/r/n",pe32.szExeFile,pe32.th32ProcessID);   
  46.         //输出进程名和进程ID   
  47.         printf(buff);   
  48.         memset(buff,0x00,1024);    
  49.         //继续枚举进程   
  50.         bProcess=Process32Next(hProcessSnap,&pe32);   
  51.     }   
  52.     CloseHandle(hProcessSnap);   
  53.     return 0;   
  54. }   
  55.   
  56.   
  57. int main(int argc, char* argv[])   
  58. {   
  59.     if(argc==2&&strcmp(argv[1],"list")==0)   
  60.     {   
  61.         GetProcess();   
  62.     }   
  63.     if(argc==3&&strcmp(argv[1],"kill")==0)   
  64.     {   
  65.         KillProcess(atoi(argv[2]));   
  66.   
  67.     }   
  68.   
  69.   
  70.     return 0;   
  71. }