`
javababy1
  • 浏览: 1240365 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

孙鑫MFC笔记教程(17)--进程间通信1(匿名管道)

 
阅读更多

孙鑫VC学习笔记:第十七讲 (二) 用匿名管道实现进程间的通信 收藏

用匿名管道实现进程间的通信:
匿名管道只能在本地主机上,父子进程之间完成通信:
步骤:
1.新建一个项目Parent
2.增加“匿名管道”子菜单以及“创建管道”、“读取数据”与“写入数据”三个菜单项。
3.在CParentView 中添加两个成员句柄:
HANDLE m_hWrite;
HANDLE m_hRead;
4.为“创建管道”菜单项实现创建管道的功能
代码如下:
注:
关闭进程和线程对象的句柄
CloseHandle (pi.hProcess);//关闭所返回的子进程句柄
CloseHandle (pi.hThread);//关闭子进程中主线程句柄
在创建新进程时,系统会建立一个主进程内核对象和一个线程内核对象,内核对象都有使用计数,
系统为内核对象赋初始的使用计数1,当CreateProgress在内部打开内核对象时,
每个对象的使用计数变为2,我们在父进程中如果不需要使用这两个句柄,
调用CloseHandle 关闭这两个句柄,
系统会将子进程的进程内核对象和线程内核对象减1,
当子进程中止运行时,系统会再将使用计数减一,此时内核对象实用计数为零,
进程内核对象和线程内核对象才能够被释放。
我们应该在不需要使用内核对象句柄的时候使用CloseHandle关闭句柄。
将结构体中所有成员置为零可以使用函数:
void ZeroMemory(PVOID Destination,SIZE_T Length);
要获得标准输入输出或标准错误句柄,使用函数:
HANDLE GetStdHandle(DWORD nStdHandle);
---------------------------------------------------------------------------------
5.接下来完成读取与写入数据的功能了
“读取数据”菜单项
“写入数据”菜单项
注.
在父进程创建管道,返回管道的读写句柄,调用CreateProcess启动子进程,
通过将子进程的标准输入输出句柄设置为管道的读写句柄,
相当于对管道的读写句柄做上标记然后传递给子进程。
在子进程中得到自己的标准输入输出句柄,相当于得到了管道的读写句柄。
匿名管道只能在父子进程间进行通信,因为匿名管道没有名字,
所以我们只有在调用CreateProcess时将管道的读写句柄传递给子进程。
---------------------------------------------------------------------------------
下面编写子线程程序:
1.新建一个项目Child添加到当前工作区
2.增加“匿名管道”子菜单以及“读取数据”与“写入数据”两个菜单项。
3.增加一个虚函数:CChildView::OnInitialUpdate(),
首先在CChildView中添加两个成员句柄:
HANDLE m_hWrite;
HANDLE m_hRead;
然后在CChildView::OnInitialUpdate()函数中得到标准输入输出句柄
m_hRead = GetStdHandle(STD_INPUT_HANDLE);
m_hWrite = GetStdHandle(STD_OUTPUT_HANDLE);
4.接下来完成读取与写入数据的功能了
读取代码与前面父进程的代码完全一样
写入代码只改了一个字符串
---------------------------------------------------------------------------------
至此,我们的程序完成了。
值得注意的是,
子进程必须由父进程打开(点击“匿名管道”菜单的“创建管道”项),它才与父进程有父子关系。
如果先打开子进程,再打开父进程,那么这两个进程并无任何关系。
---------------------------------------------------------------------------------
创建管道相关函数说明:
---------------------------------------------------------------------------------
CreatePipe
创建一个命名管道,返回一个管道的读写句柄。
The CreatePipe function creates an anonymous pipe, and returns handles to the read and write ends of the pipe.
BOOL CreatePipe(
PHANDLE
hReadPipe, // pointer to read handle用来接收管道的读取句柄
PHANDLE hWritePipe, // pointer to write handle用来接收管道的写入句柄
LPSECURITY_ATTRIBUTES lpPipeAttributes, // pointer to security attributes
DWORD nSize // 指定管道缓冲区大小
);
参数3:lpPipeAttributes用来检测返回的句柄是否可以被子进程继承。
这里不能设置为NULL,因为管道只能在父子进程间通信,
子进程要获得父进程的管道句柄只能通过继承得到。
---------------------------------------------------------------------------------
启动进程:
CreateProcess
The CreateProcess function creates a new process and its primary thread. The new process executes the specified executable file.
BOOL CreateProcess(
LPCTSTR
lpApplicationName,//
LPTSTR lpCommandLine, // pointer to command line string传递命令行参数
LPSECURITY_ATTRIBUTES lpProcessAttributes, // process security attributes
LPSECURITY_ATTRIBUTES lpThreadAttributes, // thread security attributes
BOOL bInheritHandles, // handle inheritance flag
DWORD dwCreationFlags, //用来指定控制优先级类和进程创建的附加标记
LPVOID lpEnvironment, // pointer to new environment block
LPCTSTR lpCurrentDirectory, //指向完整路径的字符指针,指定子进程当前的驱动器和目录
LPSTARTUPINFO lpStartupInfo, // pointer to STARTUPINFO指定新进程主窗口如何出现
LPPROCESS_INFORMATION lpProcessInformation
// pointer to PROCESS_INFORMATION,用来接收关于新的进程的标识信息。

);
Parameters
lpApplicationName
Pointer to a null-terminated string that specifies the module to execute.
用来指定一个可执行模块的名字。也就是可以用来设定一个可执行程序的名字
The string can specify the full path and filename of the module to execute or it can specify a partial name.
这个字符串可以指定可执行文件的完整+文件名或者指定部分名字。
In the case of a partial name, the function uses the current drive and current directory to complete the specification.
如果指定部分名字,则应用程序在当前的驱动器、当前的目录下面搜索它,如果搜索失败也不会使用搜索路径。注意:指定名字时要指定扩展名。
The lpApplicationName parameter can be NULL. In that case, the module name must be the first white space-delimited token in the lpCommandLine string.
该参数可以为NULL,这时文件的名称由第二个参数lpCommandLine中的第一个空格以前的字符指定。
If you are using a long filename that contains a space, use quoted strings to indicate where the filename ends and the arguments begin, otherwise, the filename is ambiguous.
lpCommandLine
Pointer to a null-terminated string that specifies the command line to execute. The system adds a null character to the command line, trimming the string if necessary, to indicate which file was actually used.
The lpCommandLine parameter can be NULL. In that case, the function uses the string pointed to by lpApplicationName as the command line.
If both lpApplicationName and lpCommandLine are non-NULL, *lpApplicationName specifies the module to execute, and *lpCommandLine specifies the command line. The new process can use GetCommandLine to retrieve the entire command line. C runtime processes can use the argc and argv arguments.
如果第一个参数为NULL,也就是用第二个参数来指定文件名,那么这人参数的第一个空格以前的字符会被认为是文件的名字,如果是长文件字,需要用引号把它括起来;如果没有加扩展名,则会自动加上.exe的扩展名;如果没有写全路径,则会按下下面6个路径进行搜索。
If lpApplicationName is NULL, the first white space-delimited token of the command line specifies the module name. If you are using a long filename that contains a space, use quoted strings to indicate where the filename ends and the arguments begin (see the explanation for the lpApplicationName parameter). If the filename does not contain an extension, .EXE is assumed. If the filename ends in a period (.) with no extension, or the filename contains a path, .EXE is not appended. If the filename does not contain a directory path, the system searches for the executable file in the following sequence:
  1. The directory from which the application loaded.
  2. The current directory for the parent process.
  3. Windows 95 and Windows 98: The Windows system directory. Use the GetSystemDirectory function to get the path of this directory.
    Windows NT: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is SYSTEM32.
  4. Windows NT: The 16-bit Windows system directory. There is no Win32 function that obtains the path of this directory, but it is searched. The name of this directory is SYSTEM.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.
If the process to be created is an MS-DOS - based or 16-bit Windows-based application, lpCommandLine should be a full command line in which the first element is the application name. Because this also works well for Win32-based applications, it is the most robust way to set lpCommandLine.
lpProcessAttributes
Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpProcessAttributes is NULL, the handle cannot be inherited.
用来设定新进程的安全性,以及指定父进程以后生成的子进程是否具有这个对象的句柄。
Windows NT: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new process. If lpProcessAttributes is NULL, the process gets a default security descriptor.
lpThreadAttributes
Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.
用来设定新线程的安全性,以及指定父进程以后生成的子进程是否具有这个对象的句柄。
Windows NT: The lpSecurityDescriptor member of the structure specifies a security descriptor for the main thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor.
bInheritHandles
Indicates whether the new process inherits handles from the calling process. 指定新的进程是否可以从调用进程继承句柄。
If TRUE, each inheritable open handle in the calling process is inherited by the new process. Inherited handles have the same value and access privileges as the original handles.
如果为真,则任何可继承的打开句柄都可以被新的进程所继承,
继承的句柄和原始句柄拥有同样的值和访问特权。
Return Values
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
---------------------------------------------------------------------------------
其中STARTUPINFO结构体定义如下:
STARTUPINFO
The STARTUPINFO structure is used with the CreateProcess function to specify main window properties if a new window is created for the new process. For graphical user interface (GUI) processes, this information affects the first window created by the CreateWindow function and shown by the ShowWindow function. For console processes, this information affects the console window if a new console is created for the process. A process can use the GetStartupInfo function to retrieve the STARTUPINFO structure specified when the process was created.
typedef struct _STARTUPINFO { // si
DWORD cb;
LPTSTR lpReserved;
LPTSTR lpDesktop;
LPTSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFO, *LPSTARTUPINFO;
Members
cb 指示结构体的大小,以字节为单位。
Specifies the size, in bytes, of the structure.
dwFlags
This is a bit field that determines whether certain STARTUPINFO members are used when the process creates a window. Any combination of the following values can be specified:
Value
STARTF_USESHOWWINDOW
STARTF_USEPOSITION
STARTF_USESIZE
STARTF_USECOUNTCHARS
这个值没有被指定,则dwXCountChars
dwYCountChars成员被忽略。
STARTF_USEFILLATTRIBUTE
STARTF_FORCEONFEEDBACK
STARTF_FORCEOFFFEEDBACK
STARTF_USESTDHANDLES
用来设定我们所创建的进程的标准输入、标准输出和标准错误句柄。
The CreateProcess function's fInheritHandles parameter must be set to TRUE for this to work properly.
---------------------------------------------------------------------------------
PROCESS_INFORMATION
The PROCESS_INFORMATION structure is filled in by the CreateProcess function with information about a newly created process and its primary thread.
typedef struct _PROCESS_INFORMATION { // pi HANDLE hProcess; HANDLE hThread; DWORD dwProcessId; DWORD dwThreadId; } PROCESS_INFORMATION;
Members
hProcess
Returns a handle to the newly created process. The handle is used to specify the process in all functions that perform operations on the process object.
hThread
Returns a handle to the primary thread of the newly created process. The handle is used to specify the thread in all functions that perform operations on the thread object.
dwProcessId
Returns a global process identifier (全局进程标识符)that can be used to identify a process. The value is valid from the time the process is created until the time the process is terminated.
dwThreadId
Returns a global thread identifiers (全局线程标识符)that can be used to identify a thread. The value is valid from the time the thread is created until the time the thread is terminated.
---------------------------------------------------------------------------------
GetStdHandle
The GetStdHandle function returns a handle for the standard input, standard output, or standard error device.
HANDLE GetStdHandle(
DWORD
nStdHandle // input, output, or error device
);
Parameters
nStdHandle
Specifies the device for which to return the handle. This parameter can have one of the following values:
Value Meaning
STD_INPUT_HANDLE
Standard input handle
STD_OUTPUT_HANDLE
Standard output handle
STD_ERROR_HANDLE
Standard error handle
转载自http://blog.csdn.net/huahuamoon/archive/2007/12/25/1966430.aspx
分享到:
评论

相关推荐

    MFC教程lesson 17-进程间通信.rar

    本教程聚焦于MFC中的一个重要概念——进程间通信(Inter-Process Communication,IPC)。进程间通信允许不同的进程之间交换数据,共享资源,协同工作,是Windows编程中的关键技能。Lesson 17的MFC教程将深入探讨这一...

    孙鑫MFC全套程序,基于vs2015

    《孙鑫MFC全套程序解析:基于Visual Studio 2015的实践指南》 MFC,即Microsoft Foundation Classes,是微软提供的一套C++类库,用于简化Windows应用程序的开发。孙鑫,作为国内知名的编程教育专家,以其深入浅出的...

    孙鑫C++教程(全20讲)PPT讲义源码及电子书

    最近正在学习C++,费了很多心思,分亨一下我的学习资源,孙鑫C++教程...第十七课:进程间通信 第十八课:ActiveX控件 第十九课:动态链接库 第二十课:HOOK和数据库访问 希望对大家的学习有帮助,如果不错,请帮点个赞,谢谢

    孙鑫MFC完整笔记.pdf

    孙鑫pdf文档,入门C++的好帮手,MFC类库,vc6.0,虽然版本比较老,但是在很多地方使用得仍然比较多。参考性大

    VC++ 四种进程间通信的完整实例

    VC++ 四种进程间通信的完整实例,一般来说,进程通信采取四种形式:剪贴板、匿名管道、命名管道、邮槽。孙鑫将带你用实例来验证这四种方式的优略性,进而帮助VC编程者熟悉掌握进程间通信的方方面面,并附有孙鑫老师...

    MFC-lesson3-AppWizard的原理与MFC程序框架的剖析.rar

    1. **CWinApp**:这是所有MFC应用程序的基类,包含了应用程序的全局信息和主要控制流程。CWinApp中的InitInstance函数是程序的起点,负责初始化工作,如加载资源、设置应用程序图标等。ExitInstance函数则在应用程序...

    java技术从入门到精通(孙鑫)学习笔记-Lesson2.doc

    java技术从入门到精通(孙鑫)学习笔记-Lesson2

    孙鑫VC视频教程笔记[1].doc

    【孙鑫VC视频教程笔记】是一份记录了学习VC++编程知识的文档,主要涵盖了MFC框架和SDK编程的基础概念及技巧。以下是其中涉及到的重要知识点的详细解释: 1. **StdAfx.h**:在MFC项目中,StdAfx.h文件包含了基本的...

    VS2010下孙鑫MFC第15章网络聊天室程序的实现

    孙鑫的教程是C++编程领域的经典之作,其深入浅出地讲解了MFC的使用,对于初学者和有经验的开发者都有很高的参考价值。VS2010作为一款强大的开发工具,提供了完善的MFC支持,使得我们能够更高效地构建这种类型的网络...

    VC深入详解(孙鑫笔记)自学必备

    总的来说,《VC深入详解(孙鑫笔记)自学必备》是一份全面且实用的教程,适合那些希望在VC++领域深入学习的开发者。通过这份资料,读者不仅可以学习到C++和MFC的基本知识,还能了解到高级特性和实践技巧,从而提升自己...

    vc++PPT讲义和mfc教程及c++入门基础讲解

    该资源由内附孙鑫讲解的vc++编程1-20课的PPT讲解和详细实现代码,另附c++入门基础的课程,是每位c++编程爱好者必学的课程资源c++编程进阶的必经之路。

    java技术从入门到精通(孙鑫)学习笔记

    孙鑫老师的《java技术从入门到精通》学习笔记是许多初学者和进阶者的重要参考资料。下面,我们将深入探讨这份珍贵资料中可能涵盖的核心概念。 首先,入门阶段,你需要了解Java的基础语法。包括数据类型(如基本类型...

    孙鑫 VC++ 深入详解书中源码

    《孙鑫 VC++ 深入详解》是一本深受程序员喜爱的VC++技术书籍,作者孙鑫以其深入浅出的讲解方式,详细剖析了VC++的底层机制和高级特性。书中的源码是理解理论知识的关键实践部分,通过分析和运行这些代码,读者可以更...

    经典资料:孙鑫vc++视频讲义配套的源代码20集全第1-10。

    《孙鑫VC++视频讲义配套源代码》是一份经典的编程学习资源,涵盖了从基础到进阶的VC++编程知识。这份资料由知名IT讲师孙鑫精心制作,旨在帮助学习者通过实际操作来理解VC++编程的核心概念和技术。源代码分为20个部分...

    MFC 深入详解重要笔记

    《MFC深入详解》是C++开发者在学习微软基础类库(Microsoft Foundation Classes)时的一本重要参考书籍,由孙鑫撰写。MFC是微软为Windows操作系统提供的一个C++类库,它使得开发者能够更容易地使用Windows API进行...

    语言程序设计资料:Java-笔记-孙鑫版.doc

    语言程序设计资料:Java-笔记-孙鑫版.doc

    孙鑫_VC++入门到精通_源代码

    《孙鑫_VC++入门到精通_源代码》是著名编程教育家孙鑫老师针对初学者推出的VC++学习资源,旨在帮助学习者系统地掌握Visual C++编程基础与进阶技术。该资源包含了丰富的源代码实例,覆盖了多个课程章节,如lesson 17...

    吕鑫:《VC++就业培训宝典之MFC视频教程》第十三章 第六节 MFC六大关键技术详解

    详细讲解MFC六大关键技术的原理: (1)MFC程序的初始化过程; (2)运行时类型识别(RTTI); (3)动态创建; (4)永久保存(串行化); (5)消息映射; (6)命令传递。

    孙鑫老师c++教程20

    孙鑫老师c++教程,比较全面,系统的c++教程视频。

Global site tag (gtag.js) - Google Analytics