IPC in windows

本文详细介绍了Windows操作系统中用于促进应用程序之间通信和数据共享的机制,即进程间通信(IPC)。包括文件映射、管道、远程过程调用(RPC)和Windows套接字等方法,以及它们的应用场景和优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Windows operating system provides mechanisms for facilitating communications and data sharing between applications. Collectively, the activities enabled by these mechanisms are called interprocess communications (IPC). Some forms of IPC facilitate the division of labor among several specialized processes. Other forms of IPC facilitate the division of labor among computers on a network.

Typically, applications can use IPC categorized as clients or servers. A client is an application or a process that requests a service from some other application or process. A server is an application or a process that responds to a client request. Many applications act as both a client and a server, depending on the situation. For example, a word processing application might act as a client in requesting a summary table of manufacturing costs from a spreadsheet application acting as a server. The spreadsheet application, in turn, might act as a client in requesting the latest inventory levels from an automated inventory control application.

After you decide that your application would benefit from IPC, you must decide which of the available IPC methods to use. It is likely that an application will use several IPC mechanisms. The answers to these questions determine whether an application can benefit by using one or more IPC mechanisms.

  • Should the application be able to communicate with other applications running on other computers on a network, or is it sufficient for the application to communicate only with applications on the local computer?
  • Should the application be able to communicate with applications running on other computers that may be running under different operating systems (such as 16-bit Windows or UNIX)?
  • Should the user of the application have to choose the other applications with which the application communicates, or can the application implicitly find its cooperating partners?
  • Should the application communicate with many different applications in a general way, such as allowing cut-and-paste operations with any other application, or should its communications requirements be limited to a restricted set of interactions with specific other applications?
  • Is performance a critical aspect of the application? All IPC mechanisms include some amount of overhead.
  • Should the application be a GUI application or a console application? Some IPC mechanisms require a GUI application.
  • Using a File Mapping for IPC

    File mapping enables a process to treat the contents of a file as if they were a block of memory in the process's address space. The process can use simple pointer operations to examine and modify the contents of the file. When two or more processes access the same file mapping, each process receives a pointer to memory in its own address space that it can use to read or modify the contents of the file. The processes must use a synchronization object, such as a semaphore, to prevent data corruption in a multitasking environment.

    You can use a special case of file mapping to provide named shared memory between processes. If you specify the system swapping file when creating a file-mapping object, the file-mapping object is treated as a shared memory block. Other processes can access the same block of memory by opening the same file-mapping object.

    File mapping is quite efficient and also provides operating-system–supported security attributes that can help prevent unauthorized data corruption. File mapping can be used only between processes on a local computer; it cannot be used over a network.

    Key Point:  [FileMapping是在同一台机子上两个或者多个进程间通信的一种有效方法,但是进程间必须提供同步方法]

  • Using Pipes for IPC

    There are two types of pipes for two-way communication: anonymous pipes and named pipes. Anonymous pipes enable related processes to transfer information to each other. Typically, an anonymous pipe is used for redirecting the standard input or output of a child process so that it can exchange data with its parent process. To exchange data in both directions (duplex operation), you must create two anonymous pipes. The parent process writes data to one pipe using its write handle, while the child process reads the data from that pipe using its read handle. Similarly, the child process writes data to the other pipe and the parent process reads from it. Anonymous pipes cannot be used over a network, nor can they be used between unrelated processes.

    Named pipes are used to transfer data between processes that are not related processes and between processes on different computers. Typically, a named-pipe server process creates a named pipe with a well-known name or a name that is to be communicated to its clients. A named-pipe client process that knows the name of the pipe can open its other end, subject to access restrictions specified by named-pipe server process. After both the server and client have connected to the pipe, they can exchange data by performing read and write operations on the pipe.

    Key Point:  对于不同进程使用匿名管道时必须有亲缘关系,而命名管道没用这个限制,还可以在不同机器上。

  • Using RPC for IPC

    RPC enables applications to call functions remotely. Therefore, RPC makes IPC as easy as calling a function. RPC operates between processes on a single computer or on different computers on a network.

    The RPC provided by Windows is compliant with the Open Software Foundation (OSF) Distributed Computing Environment (DCE). This means that applications that use RPC are able to communicate with applications running with other operating systems that support DCE. RPC automatically supports data conversion to account for different hardware architectures and for byte-ordering between dissimilar environments.

    RPC clients and servers are tightly coupled but still maintain high performance. The system makes extensive use of RPC to facilitate a client/server relationship between different parts of the operating system.

    Key Point:  RPC is a function-level interface, with support for automatic data conversion and for communications with other operating systems. Using RPC, you can create high-performance, tightly coupled distributed applications. For more information, see Microsoft RPC Components.

    Using Windows Sockets for IPC

    Windows Sockets is a protocol-independent interface. It takes advantage of the communication capabilities of the underlying protocols. In Windows Sockets 2, a socket handle can optionally be used as a file handle with the standard file I/O functions.

    Windows Sockets are based on the sockets first popularized by Berkeley Software Distribution (BSD). An application that uses Windows Sockets can communicate with other socket implementation on other types of systems. However, not all transport service providers support all available options.

    Key Point:  Windows Sockets is a protocol-independent interface capable of supporting current and emerging networking capabilities. For more information, see Windows Sockets 2.

### 使用 PyZMQ 实现 Windows 环境下的 IPC 通信 PyZMQ 是 ZeroMQ 的 Python 绑定库,支持多种消息传递模式以及跨平台的进程间通信(IPC)。以下是关于如何在 Windows 上使用 PyZMQ 进行 IPC 通信的具体方法。 #### 安装依赖 为了在 Windows 下运行 PyZMQ,需先安装该库及其依赖项。可以通过 pip 工具完成安装: ```bash pip install pyzmq ``` #### 配置 IPC 地址 ZeroMQ 支持通过 `ipc://` 协议实现本地机器上的进程间通信。此协议通常用于 Unix 域套接字,在 Windows 中也得到了良好支持[^1]。需要注意的是,Windows 平台下使用的路径格式略有不同,推荐采用绝对路径形式指定地址文件的位置。 例如,可以定义如下 URL 来设置 IPC 路径: ```plaintext ipc:///tmp/sockets/mysocket.ipc # Linux/MacOS style (not directly usable on Windows) ipc://./mysocket.ipc # Relative path may work cross-platform but less reliable ipc://C:/path/to/mysocket.ipc # Absolute Windows-style paths recommended ``` #### 编写代码示例 下面展示了一个简单的生产者-消费者模型来演示如何利用 PyZMQ 在同一主机的不同进程中交换数据: ##### 生产者端代码 ```python import zmq import time context = zmq.Context() socket = context.socket(zmq.PUSH) # 创建 PUSH 类型 socket socket.bind("ipc://C:/temp/zmq_test_socket.ipc") # 绑定到特定 ipc 地址 for i in range(10): message = f"Message {i}" socket.send_string(message) # 发送字符串消息 print(f"Sent: {message}") time.sleep(1) socket.close() # 关闭连接 context.term() # 清理上下文资源 ``` ##### 消费者端代码 ```python import zmq context = zmq.Context() socket = context.socket(zmq.PULL) # 创建 PULL 类型 socket socket.connect("ipc://C:/temp/zmq_test_socket.ipc") # 连接到已绑定的 ipc 地址 while True: try: message = socket.recv_string(flags=zmq.NOBLOCK) # 接收来自推送方的消息 print(f"Received: {message}") except zmq.Again: pass # 如果没有新消息则跳过处理逻辑 time.sleep(0.5) # 减少 CPU 循环频率 socket.close() # 正常退出前关闭连接 context.term() # 结束时清理上下文环境 ``` 上述例子展示了基本的一对一消息发送接收机制;实际应用中可根据需求调整为其他拓扑结构如发布订阅(pub/sub)[^4] 或请求响应(req/reply),并考虑错误恢复策略以增强健壮性。 #### 注意事项 - **权限问题**: 当创建或访问某些目录中的 `.ipc` 文件时可能会遇到权限不足的情况,请确保程序有足够的操作权利或者选择合适的存储位置。 - **兼容性测试**: 尽管理论上支持多版本操作系统间的互通,仍建议针对目标部署环境进行全面的功能验证[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值