procutil.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include "procutil.h"
  2. #include <stdio.h>
  3. namespace bbProcUtil{
  4. #if _WIN32
  5. void terminateChildren( DWORD procid,HANDLE snapshot,int exitCode ){
  6. PROCESSENTRY32 procinfo;
  7. procinfo.dwSize=sizeof( procinfo );
  8. int gotinfo=Process32First( snapshot,&procinfo );
  9. while( gotinfo ){
  10. if( procinfo.th32ParentProcessID==procid ){
  11. terminateChildren( procinfo.th32ProcessID,snapshot,exitCode );
  12. HANDLE child=OpenProcess( PROCESS_ALL_ACCESS,0,procinfo.th32ProcessID );
  13. if( child ){
  14. int res=TerminateProcess( child,exitCode );
  15. CloseHandle( child );
  16. }
  17. }
  18. gotinfo=Process32Next( snapshot,&procinfo );
  19. }
  20. }
  21. int TerminateProcessGroup( HANDLE prochandle,int exitCode ){
  22. HANDLE snapshot;
  23. int procid=GetProcessId( prochandle );
  24. //undocumented at msdn! GetProcessId returns 0 if process finished?
  25. if( !procid ) return 1;
  26. snapshot=CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS,0 );
  27. if( snapshot!=INVALID_HANDLE_VALUE ){
  28. terminateChildren( GetProcessId( prochandle ),snapshot,exitCode );
  29. CloseHandle( snapshot );
  30. }
  31. int res=TerminateProcess( prochandle,exitCode );
  32. return res;
  33. }
  34. #else
  35. char **makeargv( const char *cmd ){
  36. int n,c;
  37. char *p;
  38. static char *args,**argv;
  39. if( args ) free( args );
  40. if( argv ) free( argv );
  41. args=(char*)malloc( strlen(cmd)+1 );
  42. strcpy( args,cmd );
  43. n=0;
  44. p=args;
  45. while( (c=*p++) ){
  46. if( c==' ' ){
  47. continue;
  48. }else if( c=='\"' ){
  49. while( *p && *p!='\"' ) ++p;
  50. }else{
  51. while( *p && *p!=' ' ) ++p;
  52. }
  53. if( *p ) ++p;
  54. ++n;
  55. }
  56. argv=(char**)malloc( (n+1)*sizeof(char*) );
  57. n=0;
  58. p=args;
  59. while( (c=*p++) ){
  60. if( c==' ' ){
  61. continue;
  62. }else if( c=='\"' ){
  63. argv[n]=p;
  64. while( *p && *p!='\"' ) ++p;
  65. }else{
  66. argv[n]=p-1;
  67. while( *p && *p!=' ' ) ++p;
  68. }
  69. if( *p ) *p++=0;
  70. ++n;
  71. }
  72. argv[n]=0;
  73. return argv;
  74. }
  75. #endif
  76. }