简体   繁体   English

程序如何相互通信?

[英]How do programs communicate with each other?

How do procceses communicate with each other? procceses如何相互沟通? Using everything I've learnt to fo with programming so far, I'm unable to explain how sockets, file systems and other things to do with sending messages between programs work. 到目前为止,使用我学到的所有内容编程,我无法解释套接字,文件系统和其他在程序之间发送消息的工作方式。

Btw I use a Linux based OS if your going to add anything OS specific. 顺便说一下,如果要添加任何特定于OS的操作系统,我会使用基于Linux的操作系统。 Thanks in advance. 提前致谢。 The question's been bugging me for ages. 这个问题一直困扰着我。 I'm also guessing the kernel has something to do with it. 我也猜测内核与它有关。

In case of most IPC (InterProcess Communication) mechanisms, the general answer to your question is this: process A calls the kernel passing a pointer to a buffer with data to be transferred to process B, process B calls the kernel (or is already blocked on a call to the kernel) passing a pointer to a buffer to be filled with data from process A. 在大多数IPC(进程间通信)机制的情况下,您的问题的一般答案是:进程A调用内核将指针传递给缓冲区,数据要传输到进程B,进程B调用内核(或者已经被阻塞)在调用内核时)将指针传递给缓冲区以填充来自进程A的数据。

This general description is true for sockets , pipes , System V message queues , ordinary files etc. As you can see the cost of communication is high since it involves at least one context switch. 这种一般描述适用于套接字管道System V消息队列 ,普通文件等。正如您所看到的,通信成本很高,因为它涉及至少一个上下文切换。

Signals constitute an asynchronous IPC mechanism in which one process can send a simple notification to another process triggering a handler registered by the second process (alternatively doing nothing, stopping or killing that process if no handler is registered, depending on the signal). 信号构成一种异步IPC机制,其中一个进程可以向另一个进程发送一个简单的通知,触发由第二个进程注册的处理程序(如果没有注册处理程序,则根据信号不选择地执行任何操作,停止或终止该进程)。

For transferring large amount of data one can use System V shared memory in which case two processes can access the same portion of main memory. 对于传输大量数据,可以使用System V共享内存,在这种情况下,两个进程可以访问主内存的相同部分。 Note that even in this case, one needs to employ a synchronization mechanism, like System V semaphores , which result in context switches as well. 请注意,即使在这种情况下,也需要使用同步机制,如System V信号量 ,这也会导致上下文切换。

This is why when processes need to communicate often, it is better to make them threads in a single process. 这就是为什么当流程需要经常进行通信时,最好在单个流程中创建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM