#include <windows.h>
#include <stdio.h>
#include <Psapi.h>
#define MAX_PROCESSES 1024
#define MAX_PROCESS_NAME_LENGTH 1024
// Three hours
#define MAX_PROCESS_TIME 60*60*3
int main( int argc, char *argv[ ], char *envp[ ] )
{
DWORD pids[MAX_PROCESSES];
memset( pids, 0, sizeof( DWORD ) * MAX_PROCESSES );
DWORD rval;
EnumProcesses( pids, MAX_PROCESSES, &rval );
char szImageFileName[MAX_PROCESS_NAME_LENGTH];
int numProcesses = rval / sizeof( DWORD );
printf( "PID\tTime\n" );
for( int i = 0; i < numProcesses; i++ )
{
if( pids[i] )
{
printf( "%i\t", pids[i] );
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION, false, pids[i] );
if( hProcess )
{
memset( szImageFileName, 0, sizeof( char ) * MAX_PROCESS_NAME_LENGTH );
GetProcessImageFileName( hProcess, szImageFileName, MAX_PROCESS_NAME_LENGTH );
// Maybe check against list of allowed/disallowed applications
_FILETIME fileTime, exitTime, kernelTime, userTime;
GetProcessTimes( hProcess, &fileTime, &exitTime, &kernelTime, &userTime );
unsigned long processTime = (userTime.dwLowDateTime + kernelTime.dwLowDateTime ) / 10000000;
printf( "%i seconds\n", processTime );
CloseHandle( hProcess );
if( processTime > MAX_PROCESS_TIME )
{
printf( "Time exceeded!\n" );
// Exceeded allowed time, try to terminate it
HANDLE hPriv = OpenProcess( PROCESS_TERMINATE, false, pids[i] );
if( hPriv )
{
//TerminateProcess( hPriv, 0 );
CloseHandle( hPriv );
}
else
{
printf( "Failed to terminate process\n" );
}
// Do clever stuff, like set some secret value to tell that the time
// for today is used up. Then when we start this app we check this
// value and if he just tried to restart the computer we shut it down
// again immediately
// At a minimum we should shut down the computer now
//ShellExecute( NULL, "open", "cmd", "/C shutdown -s -t 60 -c "Your time is up!", "", SW_SHOW );
break;
}
}
else
{
printf( "Error retrieving handle to process\n" );
}
}
}
return( 0 );
}