Implement real-time Socket-based multi-process communication in Linux-Linux general technology-Linux programming and kernel information. The following is a detailed description. Level: elementary
Zhou Xin, Software Engineer
March 01, 2005
Socket is the most widely used inter-process communication mechanism in Linux. However, it cannot be directly used for real-time communication between multiple processes. This paper proposes a Socket-based multi-process communication implementation method, and provides the implementation and description of the sample program.
Socket is the most widely used inter-process communication mechanism in Linux, different from other Linux communication mechanisms, it can be used for communication between processes in a single machine, but also between processes between different machines. However, because the Socket itself does not support concurrent waiting and timeout processing, it cannot directly use multi-process mutual real-time communication.
This article proposes a Socket-based multi-process communication implementation method. The principle is to establish a process dedicated to serve as a communication server to transit communication between processes. It first starts a listening Socket to monitor connection requirements, and adds its description (Descriptor) number to a previously defined fd_set collection, the fd_set set is used to store the description numbers of the listening Socket and the communication Socket generated later. Server uses system call select to check whether any data arrives at any socket in this set in real time. If any data arrives at the listening Socket, this must be a connection request initiated by the client, therefore, a new communication Socket is generated to connect to the client, and the generated Socket description number is added to the fd_set collection, record the Client ID and the corresponding Socket description in the ID registration form. If data arrives at a communication Socket, it must be a Communication Request initiated by a client. Read the data and retrieve the ID of the receiver client. In the ID registration form, find the corresponding Socket description number, transmit data to the receiving client through the corresponding Socket.
Other processes act as clients ). The client first establishes a communication Socket to connect to the server, and then sends and receives messages through the communication Socket.
The following describes the specific program implementation and description,
First, the Server program is provided. Here we assume there are two clients for real-time communication. ClientA sends 1 character to ClientB and 2 character to ClientA.