Linux Standalone cross-process communication

Source: Internet
Author: User
Tags socket error unix domain socket

Generally speaking, through network communication (such as TCP,UDP) or shared memory can certainly achieve cross-process communication, but now it is more biased but practical methods: the use of UNIX domain communication (ordinary network connection), the use of UNIX domain communications (socketpair communication), and pipe way.

I. Using UNIX domain communication (normal network connection)

The socket API was originally designed for network communication, but later developed an IPC mechanism on the socket's framework, UNIX Domain socket. Although the network socket can also be used for interprocess communication with the same host (via loopback address 127.0.0.1), the UNIX Domain socket is more efficient for IPC: it does not need to go through the network protocol stack, does not need to package unpacking, calculate checksum, maintain serial number and answer, etc. , just copy the application layer data from one process to another. UNIX domain sockets compare to TCP sockets, where the same host is twice times faster than the latter. This is because the IPC mechanism is inherently reliable communication, and network protocols are designed for unreliable communications. UNIX Domain sockets also provide both stream-oriented and packet-oriented API interfaces, similar to TCP and UDP, but message-oriented Unixdomain sockets are also reliable and messages are neither lost nor sequenced.

The process of using the UNIX Domain socket is very similar to the network socket, and the socket () is called to create a socket file descriptor, and address family is specified as Af_unix,type to select Sock_ The Dgram or Sock_stream,protocol parameter is still specified as 0.

The most obvious difference between the UNIX domain socket and the network socket programming is that the address format is different, the structure of the Sockaddr_un, the network programming socket address is the IP address plus port number, and Unix Domain The address of the socket is the path of a socket-type file in the file system, which is created by the bind () call, and if the file already exists when bind () is called, the bind () error is returned.

#include <stdlib.h>#include<stdio.h>#include<unistd.h>#include<errno.h>#include<sys/types.h>#include<sys/socket.h>#include<netinet/inch.h>#include<sys/un.h>#include<string>usingSTD::string;voidServerservice () {intLISTENFD = socket (Af_unix, Sock_stream,0); if(LISTENFD = =-1) {perror ("Create listen FD error."); Exit (-1); }    CharPathname[] ="/tmp/my.sock"; Unlink (pathname);//If the pathname already exists in the file system, bind will fail. To do this we first call unlink to remove the pathname to prevent it from already exist    structSockaddr_un servaddr; Servaddr.sun_family=Af_unix;      strcpy (Servaddr.sun_path, pathname); if(Bind (LISTENFD, (structSOCKADDR *) &servaddr,sizeof(SERVADDR)) == -1)//If the pathname file is created successfullyPerror ("bind error"); if(Listen (LISTENFD, somaxconn) = =-1) perror ("Listen error");  while(1)      {          intCONNFD =Accept (LISTENFD, NULL, NULL); if(CONNFD = =-1)          {            if(connfd==eintr)Continue; Perror ("Accept"); }        Else        {            CharBuffer[] ="I am a boy."; Write (connfd, buffer,sizeof(buffer));        Close (CONNFD); }    } }voidClientService () {intSOCKFD = socket (Af_unix, Sock_stream,0); if(SOCKFD = =-1) perror ("Socket Error"); CharPathname[] ="/tmp/my.sock"; structSockaddr_un servaddr; Servaddr.sun_family=Af_unix;      strcpy (Servaddr.sun_path, pathname); if(Connect (SOCKFD,structSOCKADDR *) &servaddr,sizeof(SERVADDR)) == -1) perror ("Connect Error"); Charbuffer[ +]; Read (sockfd, buffer,sizeof(buffer)); printf ("read data is [%s]", buffer); Close (SOCKFD);}intMainintargcChar*argv[]) {    if(ARGC! =2) {perror ("command error."); Exit (-1); }    stringService (argv[1]); if(Service = ="Client") {clientservice (); }    Else if(Service = ="Server") {serverservice (); }    Else{perror ("command error."); return-1; }    return 0;}

two. Using UNIX domain communication (socketpair communication)

In fact, the Socketpair function is similar to the pipe function and can only be related to inter-process communication on the same host , but the anonymous pipe created by the pipe is half-duplex, and Socketpair can be thought of as creating a full-duplex pipeline. See the use of this type of communication with Nginx.

function prototypes: int socketpair (int domain, int type, int protocol, int sv[2]);

It can be seen that the UNIX communication established through a common network connection in the above example could also be used in this way.

Three. Pipe communication

Pipe is half-duplex, one end can only read, or can only write, can not be mixed.

Linux Standalone cross-process communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.