- 在windows 下编写一个控制台应用程序,命名为Child_Process。在该程序内调用CreateThread 创建两个线程,线程1每隔2秒持续不断的输出Those output come from Child_Process_Thread 1, [系统时间], 线程2每隔2秒持续不断的输出Those output come from Child_Process_Thread 2, [系统时间]
另外写一个控制台应用程序,命名为Father_Process。这个程序创建一个子进程,执行Child_Process程序。这个程序不断地输出如下行:
Those output come from Father_Process,[系统时间]
观察程序运行的结果,并对你看到的现象进行解释。 - 在windows 环境下编写一个控制台应用程序View_Process,输出系统中正在运行的进程信息,包括进程号、进程所运行的程序名、进程的启动时间。
- 通过Windows的 系统调用终止进程Child_Process,再次执行View_Process, 比较前后2次的差异。
Child_Process.cpp
#include<iostream>
#include<windows.h>
#include<time.h>
#include<thread>
using namespace std;
void thread1(){
while(1)
{
time_t now=time(0);
printf("Those output come from Child_Process_Thread 1,%s",ctime(&now));
Sleep(2000);
}
}
void thread2(){
while(1){
time_t now=time(0);
printf("Those output come from Child_Process_Thread 2,%s",ctime(&now));
Sleep(2000);
}
}
int main(){
thread t(thread1);
thread t2(thread2);
t.detach();
t2.detach();
while(1);
}
Father_Process.cpp
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<time.h>
int main()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si,sizeof(si));
si.cb=sizeof(si);
ZeroMemory(&pi,sizeof(pi));
CreateProcess("Child_Process.exe",NULL,NULL,NULL,false,0,NULL,NULL,&si,&pi);
while(1)
{
time_t now=time(0);
printf("Those output come from Father_Process, %s",ctime(&now));
Sleep(2000);
}
}
View_Process.cpp
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
void printProcessInfo(PROCESSENTRY32 pe32) {
printf("进程号: %lu\n", pe32.th32ProcessID);
printf("程序名: %s\n", pe32.szExeFile);
FILETIME createTime, exitTime, kernelTime, userTime;
SYSTEMTIME stCreateTime;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
GetProcessTimes(hProcess, &createTime, &exitTime, &kernelTime, &userTime);
FileTimeToSystemTime(&createTime, &stCreateTime);
printf("启动时间: %02d:%02d:%02d\n\n", stCreateTime.wHour, stCreateTime.wMinute, stCreateTime.wSecond);
CloseHandle(hProcess);
}
int main() {
// 获取进程快照
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
perror("创建进程快照失败");
return 1;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
// 遍历进程信息
if (Process32First(hSnapshot, &pe32)) {
do {
printProcessInfo(pe32);
} while (Process32Next(hSnapshot, &pe32));
} else {
perror("获取进程信息失败");
}
CloseHandle(hSnapshot);
system("pause");
return 0;
}