1计算机招聘笔试必记代码Word下载.docx
- 文档编号:7851940
- 上传时间:2023-05-09
- 格式:DOCX
- 页数:100
- 大小:78.04KB
1计算机招聘笔试必记代码Word下载.docx
《1计算机招聘笔试必记代码Word下载.docx》由会员分享,可在线阅读,更多相关《1计算机招聘笔试必记代码Word下载.docx(100页珍藏版)》请在冰点文库上搜索。
6.套接字(socket);
这是一种更为一般得进程间通信机制,它可用于网络中不同机器之间的进程间通信,应用非常广泛。
共享内存可以说是最有用的进程间通信方式,也是最快的IPC形式。
两个不同进程A、B共享内存的意思是,同一块物理内存被映射到进程A、B各自的进程地址空间。
进程A可以即时看到进程B对共享内存中数据的更新,反之亦然。
由于多个进程共享同一块内存区域,必然需要某种同步机制,互斥锁和信号量都可以。
Windows上共享内存是通过FileMapping实现的;
1、创建FileMapping内核对象:
CreateFileMapping;
2、打开FileMapping内核对象;
3、MapViewOfFile映射到当前进程的虚拟地址上;
4、UnmapViewOfFile回收内存地址空间(一旦用完共享内存);
示例代码:
#include
"
stdafx.h"
<
stdio.h>
Windows.h>
WinBase.h>
int
_tmain(int
argc,
_TCHAR*
argv[]){
SECURITY_ATTRIBUTESsa;
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=TRUE;
sa.lpSecurityDescriptor=NULL;
//必须这样指定,否则没有ZeroMemory的话可能是个非法的值
HANDLEshm=CreateFileMapping(INVALID_HANDLE_VALUE,&
sa,PAGE_EXECUTE_READWRITE,0,20,"
myfm"
);
if(INVALID_HANDLE_VALUE==shm){
printf("
CreateFileMappingfailed\n"
return
1;
}
*ps=(int*)MapViewOfFile(shm,FILE_MAP_ALL_ACCESS,0,0,20);
*ps=33;
UnmapViewOfFile(ps);
//这句要不要无所谓
//CloseHandle(shm);
不能在这里Close,CloseHandle使得anyerror变成2
STARTUPINFOStartupInfo;
ZeroMemory(&
StartupInfo,sizeof(STARTUPINFO));
StartupInfo.cb=sizeof(STARTUPINFO);
PROCESS_INFORMATIONProcessInformation;
BOOL
ret=CreateProcess(_T("
..\\Debug\\client.exe"
),0,0,0,
TRUE,CREATE_DEFAULT_ERROR_MODE,0,0,&
StartupInfo,&
ProcessInformation);
WaitForSingleObject(ProcessInformation.hProcess,INFINITE);
if(FALSE==ret){
%d\n"
GetLastError());
ps=(int*)MapViewOfFile(shm,FILE_MAP_ALL_ACCESS,0,0,20);
now*ps=%d\n"
*ps);
if(!
CloseHandle(shm)){
CloseHandlefailed\n"
0;
子程序代码:
#include<
argv[])
{
\nsubprocessentry\n"
HANDLEhfm=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,"
if(INVALID_HANDLE_VALUE==hfm){
OpenFileMappingfailed\n"
*ps=(int*)MapViewOfFile(hfm,FILE_MAP_ALL_ACCESS,0,0,20);
beforerewrite,ps=%d,error=%d\n"
ps,GetLastError());
*ps=44;
UnmapViewOfFile(ps);
运行结果:
subprocessentry
beforerewrite,ps=3866624,error=127
now*ps=44
Pressanykeytocontinue...
CriticalSection
//Globalvariable
CRITICAL_SECTIONCriticalSection;
intmain(void)
...
//Initializethecriticalsectiononetimeonly.
if(!
InitializeCriticalSectionAndSpinCount(&
CriticalSection,
0x00000400))
return;
//Releaseresourcesusedbythecriticalsectionobject.
DeleteCriticalSection(&
CriticalSection);
DWORDWINAPIThreadProc(LPVOIDlpParameter)
//Requestownershipofthecriticalsection.
EnterCriticalSection(&
//Accessthesharedresource.
//Releaseownershipofthecriticalsection.
LeaveCriticalSection(&
return1;
Pipe
#include<
windows.h>
tchar.h>
strsafe.h>
#defineBUFSIZE4096
HANDLEg_hChildStd_IN_Rd=NULL;
HANDLEg_hChildStd_IN_Wr=NULL;
HANDLEg_hChildStd_OUT_Rd=NULL;
HANDLEg_hChildStd_OUT_Wr=NULL;
HANDLEg_hInputFile=NULL;
voidCreateChildProcess(void);
voidWriteToPipe(void);
voidReadFromPipe(void);
voidErrorExit(PTSTR);
int_tmain(intargc,TCHAR*argv[])
{
SECURITY_ATTRIBUTESsaAttr;
printf("
\n->
Startofparentexecution.\n"
//SetthebInheritHandleflagsopipehandlesareinherited.
saAttr.nLength=sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle=TRUE;
saAttr.lpSecurityDescriptor=NULL;
//Createapipeforthechildprocess'
sSTDOUT.
if(!
CreatePipe(&
g_hChildStd_OUT_Rd,&
g_hChildStd_OUT_Wr,&
saAttr,0))
ErrorExit(TEXT("
StdoutRdCreatePipe"
));
//EnsurethereadhandletothepipeforSTDOUTisnotinherited.
SetHandleInformation(g_hChildStd_OUT_Rd,HANDLE_FLAG_INHERIT,0))
StdoutSetHandleInformation"
sSTDIN.
g_hChildStd_IN_Rd,&
g_hChildStd_IN_Wr,&
saAttr,0))
StdinCreatePipe"
//EnsurethewritehandletothepipeforSTDINisnotinherited.
SetHandleInformation(g_hChildStd_IN_Wr,HANDLE_FLAG_INHERIT,0))
StdinSetHandleInformation"
//Createthechildprocess.
CreateChildProcess();
//Getahandletoaninputfilefortheparent.
//Thisexampleassumesaplaintextfileandusesstringoutputtoverifydataflow.
if(argc==1)
Pleasespecifyaninputfile.\n"
g_hInputFile=CreateFile(
argv[1],
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if(g_hInputFile==INVALID_HANDLE_VALUE)
CreateFile"
//Writetothepipethatisthestandardinputforachildprocess.
//Dataiswrittentothepipe'
sbuffers,soitisnotnecessarytowait
//untilthechildprocessisrunningbeforewritingdata.
WriteToPipe();
printf("
Contentsof%swrittentochildSTDINpipe.\n"
argv[1]);
//Readfrompipethatisthestandardoutputforchildprocess.
ContentsofchildprocessSTDOUT:
\n\n"
ReadFromPipe();
Endofparentexecution.\n"
//Theremainingopenhandlesarecleanedupwhenthisprocessterminates.
//Toavoidresourceleaksinalargerapplication,closehandlesexplicitly.
return0;
}
voidCreateChildProcess()
//CreateachildprocessthatusesthepreviouslycreatedpipesforSTDINandSTDOUT.
TCHARszCmdline[]=TEXT("
child"
PROCESS_INFORMATIONpiProcInfo;
STARTUPINFOsiStartInfo;
BOOLbSuccess=FALSE;
//SetupmembersofthePROCESS_INFORMATIONstructure.
ZeroMemory(&
piProcInfo,sizeof(PROCESS_INFORMATION));
//SetupmembersoftheSTARTUPINFOstructure.
//ThisstructurespecifiestheSTDINandSTDOUThandlesforredirection.
siStartInfo,sizeof(STARTUPINFO));
siStartInfo.cb=sizeof(STARTUPINFO);
siStartInfo.hStdError=g_hChildStd_OUT_Wr;
siStartInfo.hStdOutput=g_hChildStd_OUT_Wr;
siStartInfo.hStdInput=g_hChildStd_IN_Rd;
siStartInfo.dwFlags|=STARTF_USESTDHANDLES;
bSuccess=CreateProcess(NULL,
szCmdline,//commandline
NULL,//processsecurityattributes
NULL,//primarythreadsecurityattributes
TRUE,//handlesareinherited
0,//creationflags
NULL,//useparent'
senvironment
scurrentdirectory
&
siStartInfo,//STARTUPINFOpointer
piProcInfo);
//receivesPROCESS_INFORMATION
//Ifanerroroccurs,exittheapplication.
bSuccess)
CreateProcess"
else
{
//Closehandlestothechildprocessanditsprimarythread.
//Someapplicationsmightkeepthesehandlestomonitorthestatus
//ofthechildprocess,forexample.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
}
voidWriteToPipe(void)
//Readfromafileandwriteitscontentstothepipeforthechild'
sSTDIN.
//Stopwhenthereisnomoredata.
DWORDdwRead,dwWritten;
CHARchBuf[BUFSIZE];
for(;
;
)
{
bSuccess=ReadFile(g_hInputFile,chBuf,BUFSIZE,&
dwRead,NULL);
bSuccess||dwRead==0)break;
bSuccess=WriteFile(g_hChildStd_IN_Wr,chBuf,dwRead,&
dwWritten,NULL);
bSuccess)break;
}
//Closethepipehandlesothechildprocessstopsreading.
CloseHandle(g_hChildStd_IN_Wr))
StdInWrCloseHandle"
voidReadFromPipe(void)
//Readoutputfromthechildprocess'
spipeforSTDOUT
//andwritetotheparentprocess'
spipeforSTDOUT.
HANDLEhParentStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
//Closethewriteendofthepipebeforereadingfromthe
//readendofthepipe,tocontrolchildprocessexecution.
//Thepipeisassumedtohaveenoughbufferspacetoholdthe
//datathechildprocesshasalreadywrittentoit.
CloseHandle(g_hChildStd_OUT_Wr))
StdOutWrCloseHandle"
bSuccess=ReadFile(g_hChildStd_OUT_Rd,chBuf,BUFSIZE,&
if(!
bSuccess=WriteFile(hParentStdOut,chBuf,
dwRead,&
voidErrorExit(PTSTRlpszFunction)
//Formatareadableerrormessage,displayamessagebox,
//andexitfromtheapplication.
LPVOIDlpMsgBuf;
LPVOIDlpDisplayBuf;
DWORDdw=GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER|
FORMAT_MESSAGE_FROM_SYSTEM|
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
d
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机 招聘 笔试 代码
![提示](https://static.bingdoc.com/images/bang_tan.gif)