命令解释器的实现
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.基本信息
➢实践题目:命令解释器的实现
➢完成人:
班级:08065801
姓名:崔洋
学号:0806580111
➢报告日期:2011年11月1日
2.实践内容简要描述
➢实践目标
1.学会在Win32环境下,创建进程的方法
2.掌握读取文件内容的方法
➢实践内容
将batch文件中所列的应用程序启动运行(批处理)
3.实践报告主要内容
➢设计思路
1从batch中读取一行字符串
2将读取的字符串作为文件名打开,若失败则显示创建进程失败的信息
3若成功,则显示子进程的PID
4重复以上操作,直至将文件batch读完
➢主要代码结构
#include
#include
#include
#include
#include
#include
using std::ifstream;
int _tmain(int argc,LPTSTR argv[]) {
STARTUPINFO StartInfo; /* Result */
PROCESS_INFORMA TION ProcessInfo; /* Result */
ZeroMemory(&StartInfo,sizeof(StartInfo));
StartInfo.cb = sizeof(StartInfo);
/* Creat a new process to execute */
/* CreateProcess parameters */
LPCTSTR lpApplicationName = NULL; // pointer to name of executable module: No module name (use command line)
LPTSTR lpCommandLine; // pointer to command line string,use to create a new process
LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL; // process security
attributes: Default
LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL; // thread security attributes: Default
BOOL bInheritHandles = FALSE; // handle inheritance flag: FALSE, the handles are not inherited
DWORD dwCreationFlags = CREATE_NEW_CONSOLE|NORMAL_PRIORITY_CLASS; /* a window per process and a normal priority*/
LPVOID lpEnvironment = NULL; // Use parent's environment block LPTSTR lpCurrentDirectory = NULL; // Use parent's starting directory LPSTARTUPINFO lpStartupInfo = &StartInfo; // pointer to STARTUPINFO struct variable
LPPROCESS_INFORMATION lpProcessInformation = &ProcessInfo ; // pointer to PROCESS_INFORMA TION struct variable
/*1. 读取文件"batch"*/
ifstream file("batch");
if(!file)
{
printf("Cannot find file \"batch\".\nPress any key to exit.");
_getch();
return 0;
}
/* 2.将读取的数据转换为命令*/
char cProcess[50];
while (!file.eof()) {
memset(cProcess, 0, sizeof(cProcess));
file >> cProcess;
if(cProcess[0] == '\0')
{
break;
}
lpCommandLine = cProcess;
if(!CreateProcess(
lpApplicationName,//创建线程
lpCommandLine,
lpProcessAttributes,
lpThreadAttributes,
bInheritHandles,
dwCreationFlags,
lpEnvironment,
lpCurrentDirectory,
lpStartupInfo,
lpProcessInformation)
) {
fprintf(stderr,"Create Process failed (%d)\n",GetLastError());
ExitProcess(2);
}
else
{
fprintf(stdout,"The Child Process: %s's PID: %d.\n", cProcess,ProcessInfo.dwProcessId);
}
// Wait until child process exits.
// WaitForSingleObject( processinfo.hProcess, INFINITE );
// fprintf(stdout,"ALL Child Process have terminated.\n")
//Sleep(500);
// Close process and thread handles.
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
};
file.close();
return (0);
}
4.实践结果
➢基本数据:
✧源程序代码行数:87
✧完成实践投入的时间(小时数):0.5
✓资料查阅时间:0.2
✓编程调试时间:0.3
➢测试数据设计
notepad.exe
calc.exe
mspaint.exe
➢测试结果分析
记事本、计算器及画图三应用程序依次打开
控制台输出:
The Child Process:notepad.exe’s PID:4420.
The Child Process:calc.exe’s PID: 4700.