/* Process Manager for Windows, 2003
 *
 * Lists the processes running and their IDs. You can terminate one
 * process just by typing its ID.
 *
 * Note : if you kill a process, the process ends after you exit the
 * program.
*/

#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>

int ProcessList(void);
int KillProcessbyID(unsigned int PID);

int main(void) {

	int id;
	int temp;

	if( ProcessList() )
		fprintf(stderr, "ProcessList Failure");

	printf("\nEnter process ID to terminate... ");
	scanf("%d", &id);

	if( KillProcessbyID((unsigned int)id)==EXIT_FAILURE ) {
		fprintf(stderr, "KillProcess Failure\n");
	}

	return 0;

}

int ProcessList(void) {

	PROCESSENTRY32 pe32;
	HANDLE hProcessSnap;
	BOOL rProcessFound;

	hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnap == INVALID_HANDLE_VALUE)
		return 1;

	pe32.dwSize=sizeof(pe32);

	rProcessFound=Process32First(hProcessSnap,&pe32);
	do {
		printf("%*s", 25, pe32.szExeFile);
		printf( "\t\t%*d\n", 4, pe32.th32ProcessID);
	}while ( rProcessFound=Process32Next(hProcessSnap,&pe32) );

	CloseHandle(hProcessSnap);

	return 0;

}

int KillProcessbyID(unsigned int PID) {

	HANDLE process;

	if( (process = OpenProcess(PROCESS_TERMINATE, 0, PID))==NULL )
		return 1;
	if( !TerminateProcess(process, (unsigned)-1) )
		return 1;

	return 0;
}
