star

搜索

RSS

RSS Link

计数器

139737
Windows屏幕飘雪

Windows进程管理实验

Star posted @ 2011年1月25日 04:31 in Windows with tags 操作系统 进程 线程 互斥 同步 信号量 临界区 命名管道 , 5392 阅读

1.线程的创建与撤销

#include <windows.h>
#include <stdio.h>

void func();

static HANDLE h1 = NULL;
static HANDLE hHandle1 = NULL;

int main(INT argc, TCHAR* argv[])
{
	int nRetCode = 0;
	DWORD dwThreadID1;
	DWORD dRes, err;
	
	//创建一个信号量 
	hHandle1 = CreateSemaphore(NULL, 0, 1, "SemaphoreName1");
	if (hHandle1 == NULL)
		puts("Semaphore Create Fail!");
	else
		puts("Semaphore Create Success!"); 
	//打开信号量 
	hHandle1 = OpenSemaphore(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE,
		NULL, "SemaphoreName1");
	if (hHandle1 == NULL)
		puts("Semaphore Open Fail!");
	else
		puts("Semaphore Open Success!"); 
	//创建子线程
	h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func,
		 NULL, 0, &dwThreadID1); 
	if (h1 == NULL)
		puts("Thread1 create Fail!");
	else
		puts("Thread1 create Success!");
	//主线程等待子线程结束 
	dRes = WaitForSingleObject(hHandle1, INFINITE);
	err  = GetLastError();
	printf("WaitForSingleObject err = %d\n", err);
	
	if(dRes == WAIT_TIMEOUT)
		printf("TIMEOUT!dRes = %d\n", dRes);
	else if(dRes == WAIT_OBJECT_0)
		printf("WAIT_OBJECT!dRes = %d\n", dRes);
	else if(dRes == WAIT_ABANDONED)
		printf("WAIT_ABANDONED!dRes = %d\n", dRes);
	else
		printf("dRes = %d\n", dRes);
	
	CloseHandle(h1);
	CloseHandle(hHandle1);
	ExitThread(0);
		 
	return nRetCode;
}

void func()	//线程函数 
{
	BOOL rc;
	DWORD err;

	puts(" NOW IN THREAD!");
	//子线程焕醒主线程,此时同步执行 
	rc = ReleaseSemaphore(hHandle1, 1, NULL);
	err = GetLastError();
	printf("ReleaseSemaphore err = %d\n", err);
	if (rc == 0)
		puts("ReleaseSemaphore Fail!");
	else
		printf("ReleaseSemaphore Success! rc = %d\n", rc);
}

2.线程的同步

#include <windows.h>
#include <stdio.h>

void ThreadName1();

static HANDLE hHandle1 = NULL;
DWORD dwThreadID1;

int main(INT argc, TCHAR* argv[])
{
	int nRetCode = 0;
	//创建一个线程 
	hHandle1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadName1, 
	NULL, 0, &dwThreadID1);
	//挂起5秒 
	Sleep(5000);
	CloseHandle(hHandle1);
	//撤消线程 
	ExitThread(0);
	return nRetCode;
}

void ThreadName1()	//线程函数 
{
	printf("Thread is Running!\n");
}

3.线程的互斥

#include <windows.h>
#include <stdio.h>

static INT count = 5;
static HANDLE h1, h2; 
LPCRITICAL_SECTION hCriticalSection;
CRITICAL_SECTION Critical;
void func1();
void func2();

int main(INT argc, TCHAR* argv[])
{
	int nRetCode = 0;
	DWORD dwThreadID1, dwThreadID2;
	//指向临界区 
	hCriticalSection = &Critical;
	InitializeCriticalSection(hCriticalSection);
	//创建线程1 
	h1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func1,
		NULL, 0, &dwThreadID1);
	if (h1 == NULL)
		puts("Thread1 create Fail!");
	else
		puts("Thread1 create Success!");
	//创建线程 
	h2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)func2,
		NULL, 0, &dwThreadID1);
	if (h2 == NULL)
		puts("Thread2 create Fail!");
	else
		puts("Thread2 create Success!");
	
	Sleep(1000);
	
	//回收处理 
	CloseHandle(h1);
	CloseHandle(h2);
	
	DeleteCriticalSection(hCriticalSection);
	ExitThread(0);
		 
	return nRetCode;
}

void func1()	//线程函数1
{
	int r1;
	
	//进入临界区 
	EnterCriticalSection(hCriticalSection);	
	r1 = count;
	Sleep(500);
	++r1;
	count = r1;
	printf("count in func1 = %d\n", count);
	//退出临界区 
	LeaveCriticalSection(hCriticalSection);
}

void func2()	//线程函数2
{
	int r2;
	
	EnterCriticalSection(hCriticalSection);
	r2 = count;
	Sleep(500);
	++r2;
	count = r2;
	printf("count in func2 = %d\n", count);
	LeaveCriticalSection(hCriticalSection);
}

4.使用命名管道实现进程通信

服务端

//Server.c
#include <windows.h>

int main(void)
{
	INT nRetCode = 0;
	INT err;
	BOOL rc;
	HANDLE hPipeHandle1;
	
	CHAR lpName[] = "\\\\.\\pipe\\myPipe";
	CHAR InBuffer[50] = "";
	CHAR OutBuffer[50] = "";
	DWORD BytesRead, BytesWrite;
	
	//创建一个命名管道 
	hPipeHandle1 = CreateNamedPipe((LPCTSTR)lpName, 
		PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC ,
		PIPE_TYPE_MESSAGE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 20, 30, 
		NMPWAIT_USE_DEFAULT_WAIT, NULL);
	
	if((hPipeHandle1 == INVALID_HANDLE_VALUE) || (hPipeHandle1 == NULL))
	{
		err = GetLastError();
		printf("Server Pipe Create Fail! err = %d\n", err);
		exit(1); 
	}
	else
		puts("Server Pipe Create Success!");
		
	while(TRUE)
	{
		//连接命名管道 
		rc = ConnectNamedPipe(hPipeHandle1, NULL);
		if (rc == 0)
		{
			err = GetLastError();
			printf("Server Pipe Connect Fail! err = %d\n", err);
			exit(2);
		}
		else
			puts("Server Pipe Connect Success!");
		strcpy(InBuffer, ""); strcpy(OutBuffer, "");
		//向命名管道中读数据 
		rc = ReadFile(hPipeHandle1, InBuffer, sizeof(InBuffer), &BytesRead, 
		NULL);
		if (rc == 0 && BytesRead == 0)
		{
			err = GetLastError();
			printf("Server Read Pipe Fail! err = %d\n", err);
			exit(2);
		}
		else
			printf("Server Read Pipe Success!\nDATA from Client is = %s\n", 
			InBuffer);
		rc = strcmp(InBuffer, "end");
		if (rc == 0)
			break;
		puts("Please Input Data to Send");
		scanf("%s", OutBuffer);
		//向命名管道中写数据 
		rc = WriteFile(hPipeHandle1, OutBuffer, sizeof(OutBuffer), &BytesWrite, 
		NULL);
		if (rc == 0)
			puts("Server Write Pipe Fail!");
		else
			puts("Server Write Pipe Success!");
		//拆除与命名管道的连接 
		DisconnectNamedPipe(hPipeHandle1);
		rc = strcmp(OutBuffer, "end");
		if (rc == 0)
			break;
	}
	puts("Now Server be END!");
	CloseHandle(hPipeHandle1);
	return nRetCode;
}

客户端

//Clinet.c
#include <windows.h>

int main(void)
{
	INT nRetCode = 0;
	INT err = 0;
	BOOL rc = 0;
	
	CHAR lpName[] = "\\\\.\\pipe\\myPipe";
	CHAR InBuffer[50] = "";
	CHAR OutBuffer[50] = "";
	DWORD BytesRead;
	
	while(TRUE)
	{
		strcpy(InBuffer, ""); strcpy(OutBuffer, "");
		puts("Input Data Please!");
		scanf("%s", InBuffer);
		rc = strcmp(InBuffer, "end");
		if (rc == 0)
		{
			//连接命名管道 
			rc = CallNamedPipe(lpName, InBuffer, sizeof(InBuffer), OutBuffer, 
				sizeof(OutBuffer), &BytesRead, NMPWAIT_USE_DEFAULT_WAIT);
			break;
		}
		//等待命名管道 
		rc = WaitNamedPipe(lpName, NMPWAIT_WAIT_FOREVER);
		if (rc == 0)
		{
			err = GetLastError();
			printf("Wait Pipe Fail! err = %d\n", err);
			exit(1);
		}
		else
			puts("Wait Pipe Success!");
		rc = CallNamedPipe(lpName, InBuffer, sizeof(InBuffer), OutBuffer, 
			sizeof(OutBuffer), &BytesRead, NMPWAIT_USE_DEFAULT_WAIT);
		rc = strcmp(OutBuffer, "end");	
		if (rc == 0)
			break;
		if (rc == 0)
		{
			err = GetLastError();
			printf("Pipe Call Fail! err = %d\n", err);
			exit(1);
		}
		else
			printf("Pipe Call Success!\nData from Server is %s\n", OutBuffer);
	}
	puts("Now Client to be End!");
	return nRetCode;
}

 

Greenhalgh 说:
2019年2月19日 13:34

The star value of the programmer is intensified for the terms for the people. The function is ensured to write a will australia for the future progress. The term is calculated for the overall good items for the humans in the field.

webnovel 说:
2019年6月01日 17:59

The web site is lovingly serviced and saved as much as date. So it should be, thanks for sharing this with us

Tyler Hamilton 说:
2020年3月20日 14:34

I really enjoy locating a website that offers you great news since I like being familiar with new things. Many times when I have been to this site I've loved the nice content on this site. An awesome website and i'll be back once more for further useful content…  meet me conference calling

Tyler Hamilton 说:
2020年4月02日 01:00

Initial You got a awesome blog .I determination be involved in plus uniform minutes. i view you got truly very functional matters , i determination be always checking your blog blesss. 메이저사이트

Tyler Hamilton 说:
2020年4月02日 01:12

wow this saintly however ,I love your enter plus nice pics might be part personss negative love being defrent mind total poeple ,사설토토

Tyler Hamilton 说:
2020年4月03日 21:02

Very interesting information, worth recommending. However, I recommend this:  온라인카지노

호빠, 호스트바, 호빠 구인, 선수하 说:
2020年7月06日 03:00

For many people this is the best solution here      see how to do it. garage door repair centereach

Anonymous 说:
2020年7月11日 19:47

For true fans of this thread I will address      is a free online!Dub

Anonymous 说:
2020年7月18日 02:10

I would recommend my profile      is important to me, I invite you to discuss this topic. smm panel

먹튀검증 说:
2020年8月16日 03:46

You should mainly superior together with well-performing material, which means that see it:

Anonymous 说:
2020年10月05日 16:17

Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... teen depression treatment center

enjoy this psalm op 说:
2020年10月15日 02:55

Below you will understand what is important, the idea provides one of the links with an exciting site:

Model Paper 2021 Pdf 说:
2020年11月16日 02:02

Here we have provided all educational board class 10th & 12th Standard Model Paper 2021 with Practice Question Paper for both medium student of the country in board wide, hope you download and practice the question bank to get a better score in all exams.

upgrade 说:
2020年11月17日 02:02

The new operating system will turn out to be the most reliable of all that Microsoft has ever released, and it will also receive native support for Android smartphones, having received full synchronization with such. According to currently available data, the presentation of Windows 12 will take place in end of 2020

Rosewe swimsuits 说:
2020年11月17日 03:16

Initial You got a awesome blog .I determination be involved in plus uniform minutes. i view you got truly very functional matters , i determination be always checking your blog blesss.

best magnetic rowing 说:
2020年11月18日 19:04

In this article understand the most important thing, the item will give you a keyword rich link a great useful website page:

make money online in 说:
2020年11月20日 17:01

These you will then see the most important thing, the application provides you a website a powerful important internet page:

buy dmt online 说:
2020年11月21日 18:08

In this article understand the most important thing, the item will give you a keyword rich link a great useful website page:

Faheem 说:
2020年11月22日 17:25

These AISSEE 2020 question papers help students to understand the pattern and difficulty level of the exam. In addition to this, each AISSEE question paper 2020 is available in three sets AISSEE Model Paper 2021. Students can download the Sainik School question paper 2021 for class 9 and 6 using the links provided below.

dark web market link 说:
2020年12月18日 17:01

This is important, though it's necessary to help you head over to it weblink:

เว็บรีวิวเว็บบาคาร่า 说:
2021年1月01日 00:55

These things are very important, good think so - I think so too...

jasa seo 说:
2021年1月06日 17:03

This is very appealing, however , it is very important that will mouse click on the connection:

JuaraFC 说:
2021年1月08日 18:17

I've proper selected to build a blog, which I hold been deficient to do for a during. Acknowledges for this inform, it's really serviceable!

judi bola 说:
2021年1月11日 00:30

Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing...

poker88 asia 说:
2021年1月16日 19:25

Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing...

idnplay poker 说:
2021年1月17日 19:27

Beaver says I also have such interest, you can read my profile here:

JuaraFC 说:
2021年1月17日 19:50

It is especially decent, though look into the tips during this home address.

brosephstalin.com 说:
2021年1月19日 13:12

I can recommend primarily decent and even responsible tips, as a result view it:

GPS moto 说:
2021年1月20日 20:31

It is especially decent, though look into the tips during this home address.

Mercedes Benz Cologn 说:
2021年1月20日 22:21

I've proper selected to build a blog, which I hold been deficient to do for a during. Acknowledges for this inform, it's really serviceable!

pkv games 说:
2021年1月21日 15:52

This is very appealing, however , it is very important that will mouse click on the connection:

Buying magic mushroo 说:
2021年1月24日 23:32

1st, deciding the strain you need is perhaps the most predominant types of Magic Mushrooms is Psilocybe Cubensis and you can locate a wide scope of various strains becoming both in the wild and inside everywhere on the world. Right now, there are more than 60 diverse Psilocybe Cubensis strains that we are aware of. Subsequently, not all Psilocybe Cubensis strains are practically a mirror image of one another. The strength and stumbling levels are distinctive in every one of these strains. On the off chance that you are searching for cheerful sentiments and bunches of chuckles, you may pick in for Magic Mushrooms, while B+ Magic Mushrooms will give you one of the hottest visual and otherworldly excursions. In the same way as other others, you might be looking for the mending advantages of psilocybin mushrooms or truffles. Before you begin investigating this segment, if it's not too much trouble note that psilocybin is an unlawful and exceptionally controlled substance in many pieces of this world. We just energize protected, capable, utilization of psilocybin mushrooms.

Asian GFE Escort in 说:
2021年2月03日 16:54

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.

nonton Layarkaca21 o 说:
2021年2月23日 03:06

It is especially decent, though look into the tips during this home address.

prime male 说:
2021年2月24日 02:26

Interestingly you write, I will address you'll find exciting and interesting things on similar topics.

Sexy Gaming 说:
2021年2月28日 16:37

I am interested in such topics so I will address page where it is cool described.

เว็บพนัน 说:
2021年3月08日 22:57

These things are very important, good think so - I think so too...

bigceme 说:
2021年3月12日 17:47

I also wrote an article on a similar subject will find it at write what you think.

dankwoods blunt 说:
2021年3月19日 20:24

It is somewhat fantastic, and yet check out the advice at this treat.

Modafinil for sale 说:
2021年3月22日 20:28

It is rather very good, nevertheless glance at the data with this handle.

poker88 说:
2021年3月23日 13:46

Acknowledges for penmanship such a worthy column, I stumbled beside your blog besides predict a handful advise. I want your tone of manuscript...

class 6 assignment 2 说:
2021年3月26日 02:22

Within this webpage, you'll see the page, you need to understand this data.

asian escort new yor 说:
2021年4月03日 04:39

"Asian upbringings make our escorts the special girls with special abilities
Our Asian escorts New York have been all brought up in Asian countries. Hence, they have all the natural charm, adorable glow all over their face and body, and the
vibes that seduce the men of American origins. Their capabilities to help you in achieving sensual climaxes through special ways makes them something that you
never nd in general."

mega888 说:
2021年4月03日 23:14

On my website you'll see similar texts, write what you think.

text mail subscriber 说:
2021年4月07日 04:10

I exploit solely premium quality products -- you will observe these individuals on:

free robux 说:
2021年4月14日 08:26

You ought to basically fantastic not to mention solid advice, which means notice:

Fortnite Skin Genera 说:
2021年4月15日 03:18

Mmm.. estimable to be here in your report or notify, whatever, I repute I should moreover process strong for my have website want I play some salubrious further updated busy in your location.

Legit Marijuana onli 说:
2021年4月15日 03:51

Welcome to the party of my life here you will learn everything about me.

ทดลอง เล่น สล็อต pp 说:
2021年4月18日 19:40

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

DIY kettlebells 说:
2021年4月27日 23:00

Your texts on this subject are correct, see how I wrote this site is really very good.

M8bet 说:
2021年5月02日 03:27

Cool you inscribe, the info is really salubrious further fascinating, I'll give you a connect to my scene.

melrose ma family da 说:
2021年5月06日 00:29

Welcome to the party of my life here you will learn everything about me.

tipandroid.com 说:
2021年5月08日 02:39

Gives you the best website address I know there alone you'll find how easy it is.

Home exercise progra 说:
2021年5月09日 22:58

Welcome to the party of my life here you will learn everything about me.

NY Asian Escorts Out 说:
2021年5月12日 01:26

Beaver says I also have such interest, you can read my profile here:

Buy N26 Verified Acc 说:
2021年5月12日 03:12

Gives you the best website address I know there alone you'll find how easy it is.

Buy WebMoney Account 说:
2021年5月12日 03:34

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

Buy Cashapp Verified 说:
2021年5月12日 22:54

I wrote about a similar issue, I give you the link to my site.

compfest.web.id 说:
2021年5月13日 16:06

On this page, you'll see my profile, please read this information.

how to get free uc i 说:
2021年5月14日 18:08

Within this webpage, you'll see the page, you need to understand this data.

why did Kakashi kill 说:
2021年5月19日 01:32

Welcome to the party of my life here you will learn everything about me.

dark web links 说:
2021年5月21日 03:54

On this page, you'll see my profile, please read this information.

dark web 说:
2021年5月21日 04:18

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

Buy Verified PayPal 说:
2021年5月21日 15:34

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

conservative news si 说:
2021年5月21日 18:26

On this page you can read my interests, write something special.

joker slot 说:
2021年5月29日 13:00

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

Emaar Dubai 说:
2021年5月31日 19:52

On this page you can read my interests, write something special.

Alpha Visage reviews 说:
2021年6月01日 00:47

During this website, you will see this shape, i highly recommend you learn this review.

Bitcoin Cash Referen 说:
2021年6月01日 02:20

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.

mega888 apk android 说:
2021年6月03日 19:17

On this page you can read my interests, write something special.

PG SLOT 说:
2021年6月04日 01:51

At this point you'll find out what is important, it all gives a url to the appealing page:

friends 说:
2021年6月04日 03:15

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have.

apktel.com 说:
2021年6月04日 19:08

Welcome to the party of my life here you will learn everything about me.

buy real id card onl 说:
2021年6月11日 02:44

You ought to basically fantastic not to mention solid advice, which means notice:

get into pc 说:
2021年6月13日 13:16

Welcome to the party of my life here you will learn everything about me.

Treatments for migra 说:
2021年6月14日 19:52

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting..

Buy SMM Service 说:
2021年6月15日 18:29

I came onto your blog while focusing just slightly submits. Nice strategy for next, I will be bookmarking at once seize your complete rises...

coconut oil for dogs 说:
2021年6月17日 00:04

Welcome to the party of my life here you will learn everything about me.

how to stop a heart 说:
2021年6月17日 02:09

Below you will understand what is important, the idea provides one of the links with an exciting site:

sarkariresultssc.com 说:
2021年6月27日 15:42

There you can download for free, see the first of these data.

Buy Facebook Busines 说:
2021年7月20日 16:01

I read this article. I think You put a lot of effort to create this article. I appreciate your work.

Buy Zelle Account 说:
2021年7月23日 19:55

Interestingly you write, I will address you'll find exciting and interesting things on similar topics.

When is blood pressu 说:
2021年7月27日 18:54

I would recommend my profile is important to me, I invite you to discuss this topic.

slot pg 说:
2021年7月30日 02:55

I've proper selected to build a blog, which I hold been deficient to do for a during. Acknowledges for this inform, it's really serviceable!

Public Financial Man 说:
2022年8月03日 17:23

The idea brought to track the funds released through various central government schemes. This acknowledge proper expenditure at every level of scheme implementation. Public Financial Management System is an online software develop by the Controller General of Accounts, Department of Expenditure, Ministry of Finance, Government of India. Public Financial Management System The idea brought to track the funds released through various central government schemes. This acknowledge proper expenditure at every level of scheme implementation.

Public Financial Man 说:
2022年8月03日 17:24

The idea brought to track the funds released through various central government schemes. This acknowledge proper expenditure at every level of scheme implementation. Public Financial Management System is an online software develop by the Controller General of Accounts, Department of Expenditure, Ministry of Finance, Government of India. Public Financial Management System The idea brought to track the funds released through various central government schemes. This acknowledge proper expenditure at every level of scheme implementation.

NCERT Term 1 Questio 说:
2022年9月29日 20:02

Candidates who to know the examination pattern or question paper style and want topic wise important questions for all subjects, NCERT Term 1 Question Paper Class 10 with those candidates in mind here we supplied the NCERT Term-1 Sample Paper 2023 Class 10 for Session exams of SA, FA and Assignments of all subjects and languages as per the newly revised syllabus & curriculum. Candidates who to know the examination pattern or question paper style and want topic wise important questions for all subjects.Candidates who to know the examination pattern or question paper style and want topic wise important questions for all subjects.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter