操作系统-进程和线程管理

  1. 在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,[系统时间]
    观察程序运行的结果,并对你看到的现象进行解释。
  2. 在windows 环境下编写一个控制台应用程序View_Process,输出系统中正在运行的进程信息,包括进程号、进程所运行的程序名、进程的启动时间。
  3. 通过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;
}
  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值