CreateProcess( LPCTSTR lpApplicationName, //pointer to name of executable moudle LPTSTR cmdLine, //pointer to command line string LPSECURITY_ATTRIBUTES lpProcessAttributes, //pointer to process security attributes LPSECURITY_ATTRIBUTES lpThreadAttributes, //pointer to theread security attributes BOOL bInheritHandle , //handle inheritance flag DWord dwCreationFlag,//various creation flags LPVOID lpEnviroment,//Enviroment variable LPCTSTR lpCurrentDirectory, //Child's current directory LPSTARTUPINFO lpStartupInfo, //pointer to StartupInfo LPPROCESS_INFORMATION lpProcessInformation //pointer to PROCESS_INFORMATION ) 虽然有很多参数,不过在现阶段的实验级别,大多数参数只要用默认值即可。
while(fgets(cmdLine,MAX_LINE_LEN,fid)!=NULL) { //Read a command from the file if(cmdLine[strlen(cmdLine)-1]=='\n') cmdLine[strlen(cmdLine)-1]='\0';//Remove NEWLINE //Create a new process to execute the command ZeroMemory(&startInfo,sizeof(startInfo)); startInfo.cb=sizeof(startInfo); if(!CreateProcess( NULL,//File name of executable cmdLine,//command line processA,//Process inherited security threadA, //Thread inherited security shareRights,//Rights propagation creationMask,//various creation flags
enviroment,//Enviroment variable curDir, //Child's current directory &startInfo, &procInfo ) ) { fprintf(stderr,"CreatProcess failed on error %d\n",GetLastError()); ExitProcess(0); } } //Terminate after all commands have finished. return 0; } 通过上面这段极其简洁的代码,完成了看似有些难度的任务,让我们充分感受到采用一些高级的编程手段所带来的便捷与高效.
HANDLE CreateThread (LPSECURITY_ATTRIBUTES lpThreadAttributes,//pointer to thread security attributes DWORD dwStackSize,//initial thread stack size, in bytes LPSECURITY_START_ROUTINE lpStartAddress,//pointer to thread function LPVOID lpParameter,//argument for new thread DWORD dwCreationFlags,//creation flags LPDWORD lpThreadId //pointer to returned thread identifier ) 其中,在本实验阶段比较重要的参数是第三和第四个:
threadNum=parseArgToInt(argv[1]); runTime=parseArgToInt(argv[2]); //Get the time the threads should run,runtime //Calculate time to halt // runTime=60;/*in seconds.*/
GetSystemTime(&now); printf("mthread:Suite starting aty system time%d,%d,%d\n",now.wHour,now.wMinute,now.wSecond); stopTimeSecond=(now.wSecond+(WORD)runTime)%60;
sleepTime=1000+30*(int)eRandom(50+tNo); Sleep(sleepTime); printf("I am thread No.%d,sleep sec:%ds\n",tNo,sleepTime); }
//Terminate return result; }
int parseArgToInt(char* inNumChar) { int equipData=0,i=0; while(inNumChar[i]>='0'&&inNumChar[i]<='9') { equipData=10*equipData+(inNumChar[i]-48); i++; } return equipData; }
Type eRandom(int upLimit) { Type tmpData; do { tmpData=((Type)rand()/(Type)32767)*(Type)100.0*(Type)upLimit; } while(tmpData>upLimit); return tmpData; }