Online Judge测试部分的代码
Online Judge是一个根据程序的输入输出测试程序正确性的Web程序,一般用于ACM/ICPC的训练。这是我做的测试部分的源代码,主要是限定程序的运行时间和占用的空间,以及程序的输入输出重定向。限时做得很粗糙,仅仅使用了WaitForSingleObject,不能得到真正的CPU时间。用法:test <progname> <input> <output> <time> <memory>
<progname> 要测试的程序名
<input> 输入数据
<output> 程序输出
<time> 时间限制(单位:ms)
<memory> 存储空间限制(单位:KB)
返回值:正确结束返回0;超时——1,超出存储限制——2。
#include <windows.h>#include <psapi.h>#include <stdio.h>#include <string.h>#include <stdlib.h>int main(int argc, char **argv){char *app_name=argv;char *input_file=argv;char *output_file=argv;char *time_str=argv;char *mem_str=argv;int time_limit=atoi(time_str);DWORD mem_limit=atoi(mem_str);mem_limit<<=10;SECURITY_ATTRIBUTES sa;sa.nLength=sizeof(SECURITY_ATTRIBUTES);sa.lpSecurityDescriptor=NULL;sa.bInheritHandle=TRUE;HANDLE hInput=CreateFile(input_file,GENERIC_READ,0,&sa,OPEN_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL);HANDLE hOutput=CreateFile(output_file,GENERIC_WRITE,0,&sa,CREATE_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL);STARTUPINFO si={sizeof(si)};GetStartupInfo(&si);si.dwFlags=STARTF_USESTDHANDLES;si.hStdInput=hInput;si.hStdOutput=hOutput;PROCESS_INFORMATION pi;ZeroMemory(&pi,sizeof(pi));char *szCommandLine;szCommandLine=(char *)calloc(sizeof(char),(strlen(app_name)+1));strcpy(szCommandLine,app_name);CreateProcess(NULL,szCommandLine,NULL,NULL,TRUE,CREATE_NO_WINDOW,NULL,NULL,&si,&pi);DWORD status=WaitForSingleObject(pi.hProcess,time_limit);PROCESS_MEMORY_COUNTERS memInfo;GetProcessMemoryInfo(pi.hProcess,&memInfo,sizeof(memInfo));int ret;if (status!=WAIT_OBJECT_0){ret=1;TerminateProcess(pi.hProcess,0);}else{if (memInfo.PeakWorkingSetSize>mem_limit){ret=2;}else{ret=0;}}CloseHandle(pi.hThread);CloseHandle(pi.hProcess);CloseHandle(hInput);CloseHandle(hOutput);return ret;}
页:
[1]