TERMINATE PROCESS: not working

Ok, i REALLY HATE win API, but it executes faster than batch commands, bla bla bla.

So, first:

What is a 'HANDLE' supposed to be? a String? an Integer? The compiler says it's void, but it doesn't even compile the thing:

C:\Users\Desktop\C++\Program Boundry Enforcement System\main.cpp|97|error: cannot convert '__gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type {aka std::basic_string<char>}' to 'HANDLE {aka void*}' in assignment|


so, if i got a vector of strings with the image name of each process that needs to be terminated, how can i convert to HANDLES???

Second:

What's with the "in"'s and "out"'s??? It makes no sense:

_In_ HANDLE hProcess,


"_in_" I going to try and guess: a variable type?

Third:

UINT- again: is that a string, int, how am i supposed to convert us-able data into whatever a "UINT" is?

I'm sorry, but it's so frustrating trying to learn this on my own.

Thank you so much for your time!
UINT is declared as typedef unsigned int UINT .

A HANDLE must only be obtained from win32 APIs and only used as parameter to other win32 APIs, why do you want to convert it ?

See this link for Windows data types:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx


In your case use OpenProcess() to obtain the handle required for TerminateProcess() if you have the process ID.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx
Last edited on
so.... how can i even get the handle, when I don't even know the process ID??

HANDLE WINAPI OpenProcess(
_In_ DWORD dwDesiredAccess,
_In_ BOOL bInheritHandle,
_In_ DWORD dwProcessId
);


where does "the process image name.exe" fit into this?

if DWORDs are integers, and the only other thing there is a bool, how am I supposed to use this to get the process' handle?

(quite literally, because as you can see, I don't know much about the windows API)
Last edited on
You don't convert an image name to a handle...

You have to enumerate the running processes and find the ones which are running the image you're looking for, and get the process ids from them. You then feed that into OpenProcess.

One way to enumerate through the processes is the Toolhelp API: CreateToolhelp32Snapshot, Process32First, and Process32Next.

Then you're got to contend with the security privileges, etc.

Andy

PS _In_, _Etc_ are nothing to do with C++ -- they are macros which compile to nothing. But they are used by the Microsoft's static analysis tool (they're par of the Source Code Annotation Language - aka SAL).

PPS See also

Taking a Snapshot and Viewing Processes (Windows)
http://msdn.microsoft.com/en-gb/library/windows/desktop/ms686701%28v=vs.85%29.aspx

How To Terminate an Application "Cleanly" in Win32
http://support.microsoft.com/kb/178893
Last edited on
1st problem:

hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );


"TH32CS_SNAPPROCESS" comes from absolutely nowhere. This is the problem i have with win API, they have all these variables that aren't declared.

Could someone please explain how this is supposed to even work?

Also, ty andy and modoran for your replies, they were very helpful, but raise a lot more questions than they answer....
TH32CS_SNAPPROCESS doesn't come from nowhere, it's in TlHelp32.h

Searching MSDN, or Googling, for CreateToolhelp32Snapshot, as I'd assume you'd do to learn more about the call, you would have found:

CreateToolhelp32Snapshot function (Windows)
http://msdn.microsoft.com/en-gb/library/windows/desktop/ms682489%28v=vs.85%29.aspx

which tells you, in the Requirements section:

Header    TlHelp32.h
Library   Kernel32.lib
DLL       Kernel32.dll

This hold for most if not all Windows API calls.

Whenever I come across an API call I don't know, or use one I've not used for a while, then that's what I do!

Andy
Last edited on
so....

Windows doesn't even follow the rules?

The way I understand it, function calls look like this:

Function_name([arguments]);
@IWishIKnew
Where are you getting that? Maybe looking at this sample app that gets a process snapshot (from the link andywestken provided) will help http://msdn.microsoft.com/en-gb/library/windows/desktop/ms686701(v=vs.85).aspx
Last edited on
I think you want to terminate a specific process, right?



TerminateProcess requires a valid process HANDLE (process address). The HANDLE should have the attribute PROCESS_TERMINATE with a correct ProcessId. Use the function OpenProcess.

If you want to find a specific process, you'll need to follow some steps :

tlhelp32.h


- Get a HANDLE value via the function CreateToolhelp32Snapshot. Specify the value TH32CS_SNAPPROCESS here.
- Create a PROCESSENTRY32 variable. (Not pointer)
- Use the Process32First,and Process32Next loop.

And, you asked what is HANDLE? Actually it's a PVOID value (*void), means it's a unknown pointer variable definition.
This definition type specifies a specific address.

A reference link : http://www.cplusplus.com/forum/beginner/86531/

Need more details or examples?
Hope all goes well . <:)
Last edited on
Get a HANDLE value via the function CreateToolhelp32Snapshot. Specify the value TH32CS_SNAPPROCESS here.


Specify the value of what??

What does that "value" represent??
"HANDLE value" = the handle of the process you want to terminate

"the value TH32CS_SNAPPROCESS" = the value of dwFlags in

1
2
3
4
HANDLE WINAPI CreateToolhelp32Snapshot(
  _In_  DWORD dwFlags,
  _In_  DWORD th32ProcessID
);


See

CreateToolhelp32Snapshot function (Windows)
http://msdn.microsoft.com/en-gb/library/windows/desktop/ms682489%28v=vs.85%29.aspx
Last edited on
You don't need to know what TH32CS_SNAPPROCESS or HANDLE is, just follow the function documentation as it sais in MSDN.

Did you even read it ? If yes, read it again more carefully !
@ modoran

Yes I did, and didn't understand a word of it because I don't know what a handle is, or how winAPI even works. I also don't understand why you have to write a humungus function just to simplify the dang thing to a "create_process(string process_name)".

Yes, yes... a handle is the "handle of the process you want to terminate"... but WHAT is it: a string?? How am I supposed to 'treat' a handle? Is is a variable at all? is it as simple as HANDLE a_handle = "process_name.exe"??

and not to mention this:

1
2
3
4
5
HANDLE WINAPI OpenProcess(
  _In_  DWORD dwDesiredAccess,
  _In_  BOOL bInheritHandle,
  _In_  DWORD dwProcessId
);


ok, i will give this a wack:

1
2
3
BOOL WINAPI TerminateProcess(
  OpenProcess(/*123?? where do i get this?*/123, /*false??  mabey?*/false, "firefox.exe"),
  /*ummmm  whatever??*/  0);


Tell me if i'm wrong (I'm pretty sure I am...).
-OpenProcess
Third parameter requires a DWORD value (means an unsigned integer value). So, you can't attach your string to this slot. This causes a compling error.

It is a ProcessId, have you read it carefully?
How to get it? Use the Process32First, Process32Next and CreateToolhelp32Snapshot (TH32CS_SNAPPROCESS,0) with structure (PROCESSENTRY32) (Process linear search)
Need more details or examples?
Tip : (Another solution & instant result) Open Task Manager and see the process PID
Edit : The first parameter :
If you want to terminate a process, please, specify the value PROCESS_TERMINATE here.
Hope all goes well, dude :)
Last edited on
This sample code is taken from MSDN, from the link already posted in this topic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>

//  Forward declarations:
BOOL GetProcessList( );
BOOL ListProcessModules( DWORD dwPID );
BOOL ListProcessThreads( DWORD dwOwnerPID );
void printError( TCHAR* msg );

int main( void )
{
  GetProcessList( );
  return 0;
}

BOOL GetProcessList( )
{
  HANDLE hProcessSnap;
  HANDLE hProcess;
  PROCESSENTRY32 pe32;
  DWORD dwPriorityClass;

  // Take a snapshot of all processes in the system.
  hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
  if( hProcessSnap == INVALID_HANDLE_VALUE )
  {
    printError( TEXT("CreateToolhelp32Snapshot (of processes)") );
    return( FALSE );
  }

  // Set the size of the structure before using it.
  pe32.dwSize = sizeof( PROCESSENTRY32 );

  // Retrieve information about the first process,
  // and exit if unsuccessful
  if( !Process32First( hProcessSnap, &pe32 ) )
  {
    printError( TEXT("Process32First") ); // show cause of failure
    CloseHandle( hProcessSnap );          // clean the snapshot object
    return( FALSE );
  }

  // Now walk the snapshot of processes, and
  // display information about each process in turn
  do
  {
    _tprintf( TEXT("\n\n=====================================================" ));
    _tprintf( TEXT("\nPROCESS NAME:  %s"), pe32.szExeFile );
    _tprintf( TEXT("\n-------------------------------------------------------" ));

    // Retrieve the priority class.
    dwPriorityClass = 0;
    hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
    if( hProcess == NULL )
      printError( TEXT("OpenProcess") );
    else
    {
      dwPriorityClass = GetPriorityClass( hProcess );
      if( !dwPriorityClass )
        printError( TEXT("GetPriorityClass") );
      CloseHandle( hProcess );
    }

    _tprintf( TEXT("\n  Process ID        = 0x%08X"), pe32.th32ProcessID );
    _tprintf( TEXT("\n  Thread count      = %d"),   pe32.cntThreads );
    _tprintf( TEXT("\n  Parent process ID = 0x%08X"), pe32.th32ParentProcessID );
    _tprintf( TEXT("\n  Priority base     = %d"), pe32.pcPriClassBase );
    if( dwPriorityClass )
      _tprintf( TEXT("\n  Priority class    = %d"), dwPriorityClass );

    // List the modules and threads associated with this process
    ListProcessModules( pe32.th32ProcessID );
    ListProcessThreads( pe32.th32ProcessID );

  } while( Process32Next( hProcessSnap, &pe32 ) );

  CloseHandle( hProcessSnap );
  return( TRUE );
}


BOOL ListProcessModules( DWORD dwPID )
{
  HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
  MODULEENTRY32 me32;

  // Take a snapshot of all modules in the specified process.
  hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );
  if( hModuleSnap == INVALID_HANDLE_VALUE )
  {
    printError( TEXT("CreateToolhelp32Snapshot (of modules)") );
    return( FALSE );
  }

  // Set the size of the structure before using it.
  me32.dwSize = sizeof( MODULEENTRY32 );

  // Retrieve information about the first module,
  // and exit if unsuccessful
  if( !Module32First( hModuleSnap, &me32 ) )
  {
    printError( TEXT("Module32First") );  // show cause of failure
    CloseHandle( hModuleSnap );           // clean the snapshot object
    return( FALSE );
  }

  // Now walk the module list of the process,
  // and display information about each module
  do
  {
    _tprintf( TEXT("\n\n     MODULE NAME:     %s"),   me32.szModule );
    _tprintf( TEXT("\n     Executable     = %s"),     me32.szExePath );
    _tprintf( TEXT("\n     Process ID     = 0x%08X"),         me32.th32ProcessID );
    _tprintf( TEXT("\n     Ref count (g)  = 0x%04X"),     me32.GlblcntUsage );
    _tprintf( TEXT("\n     Ref count (p)  = 0x%04X"),     me32.ProccntUsage );
    _tprintf( TEXT("\n     Base address   = 0x%08X"), (DWORD) me32.modBaseAddr );
    _tprintf( TEXT("\n     Base size      = %d"),             me32.modBaseSize );

  } while( Module32Next( hModuleSnap, &me32 ) );

  CloseHandle( hModuleSnap );
  return( TRUE );
}

BOOL ListProcessThreads( DWORD dwOwnerPID ) 
{ 
  HANDLE hThreadSnap = INVALID_HANDLE_VALUE; 
  THREADENTRY32 te32; 
 
  // Take a snapshot of all running threads  
  hThreadSnap = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 ); 
  if( hThreadSnap == INVALID_HANDLE_VALUE ) 
    return( FALSE ); 
 
  // Fill in the size of the structure before using it. 
  te32.dwSize = sizeof(THREADENTRY32); 
 
  // Retrieve information about the first thread,
  // and exit if unsuccessful
  if( !Thread32First( hThreadSnap, &te32 ) ) 
  {
    printError( TEXT("Thread32First") ); // show cause of failure
    CloseHandle( hThreadSnap );          // clean the snapshot object
    return( FALSE );
  }

  // Now walk the thread list of the system,
  // and display information about each thread
  // associated with the specified process
  do 
  { 
    if( te32.th32OwnerProcessID == dwOwnerPID )
    {
      _tprintf( TEXT("\n\n     THREAD ID      = 0x%08X"), te32.th32ThreadID ); 
      _tprintf( TEXT("\n     Base priority  = %d"), te32.tpBasePri ); 
      _tprintf( TEXT("\n     Delta priority = %d"), te32.tpDeltaPri ); 
      _tprintf( TEXT("\n"));
    }
  } while( Thread32Next(hThreadSnap, &te32 ) ); 

  CloseHandle( hThreadSnap );
  return( TRUE );
}

void printError( TCHAR* msg )
{
  DWORD eNum;
  TCHAR sysMsg[256];
  TCHAR* p;

  eNum = GetLastError( );
  FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
         NULL, eNum,
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
         sysMsg, 256, NULL );

  // Trim the end of the line and terminate it with a null
  p = sysMsg;
  while( ( *p > 31 ) || ( *p == 9 ) )
    ++p;
  do { *p-- = 0; } while( ( p >= sysMsg ) &&
                          ( ( *p == '.' ) || ( *p < 33 ) ) );

  // Display the message
  _tprintf( TEXT("\n  WARNING: %s failed with error %d (%s)"), msg, eNum, sysMsg );
}
@modoran

Certainly, Microsoft samples are really perfect, but the sample you mentioned requires lots of knowledge and some of this are not related.... The OP now is still asking about Variable definition and how to use a WinAPI function. So, the OP should take a simpler sample or a snippet code example. That's better.
Terminating a process is not beginner level code on Windows. It requires knowledge about the Win32 security mechanism and how Windows manages processes. There is no simpler answer.

The call to TerminateProcess itself is the easy bit. It's finding the handle from the image path and adjusting the user privileges which are the problem.

Andy

PS Regarding handles...

A handle is an abstract (typically integer) identifier; for Win32, it's a 32 bit integer, for Win64 it's a 64 bit one. You give the handle to Windows and it uses it to finds the corresponding object. How it's actually stored inside is hidden from you. Note that the handle approach is not unique to Windows.

Handle (computing)
http://en.wikipedia.org/wiki/Handle_%28computing%29

What is a Windows Handle?
http://stackoverflow.com/questions/902967/what-is-a-windows-handle
so... Mabey some direction with the windows API would be helpful. I'm not particularly well versed with it.

Thank you for all of your help, I really really appreciate it!
Topic archived. No new replies allowed.