Windows进程的创建与销毁

来源:互联网 发布:怎么用淘宝客买东西 编辑:程序博客网 时间:2024/06/13 01:27

今天课上做了关于进程创建与控制的实验,简单记录下来:


实验题目

① 掌握Windows进程的创建和销毁API的调用方法;编程代码,在程序中创建和销毁一个Word进程;
② 能够挂起和激活被创建进程的主线程;
③ 通过Windows进程管理器查看系统进程列表的变化。

实验指导

①创建进程的API
BOOL CreateProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCTSTR lpCurrentDirectory,
LPSTARTUPINFO lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
);
例程:
void main( VOID ){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line).
“MyChildProcess”, // Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent’s environment block.
NULL, // Use parent’s starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi ) // Pointer to PROCESS_INFORMATION structure.
) {
ErrorExit( “CreateProcess failed.” );
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
② 销毁进程API
BOOL TerminateProcess(
HANDLE hProcess,
UINT uExitCode
);
③ 挂起进程的主线程API
DWORD SuspendThread(
HANDLE hThread
);
④激活进程的主线程API
DWORD ResumeThread(
HANDLE hThread
);

代码块

我在实验中写的代码如下:

#include"iostream"  #include"windows.h"  using namespace std;void  main(VOID) {    STARTUPINFO si;    PROCESS_INFORMATION pi;    ZeroMemory(&si, sizeof(si));    si.cb = sizeof(si);    ZeroMemory(&pi, sizeof(pi));    if (!CreateProcess(NULL, "E:\\office\\Office14\\WINWORD.EXE", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))    {        fprintf(stderr, "Createprocess Failed ");    }    int x;    while (true) {        cout << "请输入要选择的操作:\n0:销毁进程\n1:挂起进程\n2:激活进程\n3:退出\n";        cin >> x;        switch (x) {        case 0:            if (TerminateProcess(pi.hProcess, 0))                cout << "销毁进程成功" << endl;            else                cout << "销毁失败" << endl;            break;        case 1:            if (SuspendThread(pi.hThread))                cout << "挂起进程成功" << endl;            else                cout << "挂起失败" << endl;            break;        case 2:            if (ResumeThread(pi.hThread))                cout << "激活进程成功" << endl;            else                cout << "激活失败" << endl;            break;        case 3:            exit(0);        default:            cout << "选项不正确" << endl;        }    }    system("pause");}

其实很简单的操作,主要要注意的就是CreateProcess这个方法的各个参数,以及要启动的一定是一个.exe文件

原创粉丝点击