Cross-process communication using UNIX domain sockets

Source: Internet
Author: User
Tags unix domain socket

Introduction to UNIX domain sockets

UNIX domain sockets are described in advanced Programming for UNIX environments as follows:

Although the Socketpair function creates a pair of sockets that are connected to each other, each socket does not have a name. This means that unrelated processes cannot use them.

We can name UNIX domain sockets and can use them for the sign service. However, it is important to note that Unxi and sockets use different addresses than Internet domain sockets.

The address of a UNIX domain socket is sockaddr_un represented by a struct.

In linux2.4.22, the sockaddr_un structure is defined in the following form in the file

    struct sockaddr_un{    //AF_UNIX    char sun_path[108//pathname    };

sun_pathMembers contain a name, and when we bind an address to a UNIX domain socket, the system creates a type file with that path S_IFSOCK . This file is used only to inform the client process of the socket name. The file cannot be opened, nor can it be used by the application for communication.

If the file already exists when we try to bind the address, the bind request fails. When the socket is closed, the file is not automatically deleted, so we must ensure that the file is unlinked before the application terminates.

The server process can use the standard bind, listen, and accept functions to schedule a unique UNIX domain connection for the client process. The client process connects to the server process using Connect;

After the server process accepts the connect request, there is a unique connection between the server process and the client process. This style is similar to the operation of Internet sockets.

Programming with a named UNIX domain socket process

Example the ability to implement a Client-server interaction using UNIX domain sockets

Server-side code is as follows: Create a UNIX socket and bind to the /tmp/test.sock next to listen, when there is a client connection fork out the child process for processing, the child process is responsible for receiving data and printing to the screen:

/****************************************************************************** * File name: TestUnixSocket.cpp * File Description: UNIX domain socket Test * Date Created: 2015-04-02 * Author: Casheywen ****************************************************************** ************/#include <iostream>using namespace STD;#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/un.h>#define LOG_ERR (FMT, args ...) fprintf (stderr, "pid:%d|" FMT "\ n", Getpid (), # #args)#define LOG_INFO (FMT, args ...) fprintf (stdout, "pid:%d|" FMT "\ n", Getpid (), # #args)intCreateunixsocket (Const Char*pszpath) {intIFd = socket (Af_unix, Sock_stream,0);if(IFd <0) {Log_err ("Create Socket Fail:%s", Strerror (errno));return-1; }structSockaddr_un staddr;memset(&AMP;STADDR,0,sizeof(STADDR)); staddr.sun_family = Af_unix;strncpy(Staddr.sun_path, Pszpath,sizeof(Staddr.sun_path));intIRet = Bind (IFd, (structSOCKADDR *) &staddr,sizeof(STADDR));if(IRet <0) {Log_err ("Bind Fail:%s", Strerror (errno));return-1; }returnIFd;}intMainintargcChar*argv[]) {Const CharSzsocketpath[] ="/tmp/test.sock";if(0= = Access (Szsocketpath, F_OK)) {unlink (Szsocketpath); }intIFd = Createunixsocket (Szsocketpath);if(IFd <0) {Log_err ("Createunixsocket%s Fail", Szsocketpath);return 1; }intIRet =0; while(true) {IRet = Listen (IFd,5);if(IRet <0) {Log_err ("Listen Fail:%s", Strerror (errno));return 1; } log_info ("Listening on%s", Szsocketpath);structSockaddr_un stclientaddr; socklen_t Nclientaddrlen =sizeof(STCLIENTADDR);memset(&AMP;STCLIENTADDR,0,sizeof(STCLIENTADDR));intICLIENTFD = Accept (IFd, (structSOCKADDR *) &stclientaddr, &nclientaddrlen);if(Iclientfd <0) {Log_err ("Accept Fail:%s", Strerror (errno));return 1; } log_info ("connected:client Addr%s", Stclientaddr.sun_path); pid_t pid = fork ();if(PID = =0)//Parent Process{Close (ICLIENTFD);Continue; }Else if(PID <0) {Log_err ("Fork Fail:%s", Strerror (errno)); }Characbuf[4096] = {0};inticnt =0; while(icnt = Read (ICLIENTFD, Acbuf,sizeof(ACBUF)))) {Log_info ("Read%d bytes:[%s]", icnt, ACBUF); } log_info ("disconnected:client Addr%s", Stclientaddr.sun_path);return 0; }}

The client code is as follows: Create a UNIX socket and connect the /tmp/test.sock listening socket, read the data from the standard input and send it to the server side via the socket

/****************************************************************************** * File name: Client.cpp * File Description: UNIX domain socket Test * Date Created: 2015-04-02 * Author: Casheywen ****************************************************************** ************/#include <iostream>using namespace STD;#include <errno.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/un.h>#include <signal.h>#define LOG_ERR (FMT, args ...) fprintf (stderr, "pid:%d|" FMT "\ n", Getpid (), # #args)#define LOG_INFO (FMT, args ...) fprintf (stdout, "pid:%d|" FMT "\ n", Getpid (), # #args)voidSigpipehandler (intIsigno) {Log_err ("Sigpipe received");Exit(1);}BOOLConnectunixsocket (Const Char*pszpath,intIFD) {structSockaddr_un staddr;memset(&AMP;STADDR,0,sizeof(STADDR)); staddr.sun_family = Af_unix;strncpy(Staddr.sun_path, Pszpath,sizeof(Staddr.sun_path));intIRet = Connect (IFd, (structSOCKADDR *) &staddr,sizeof(STADDR));if(IRet <0) {Log_err ("Connect Fail:%s", Strerror (errno));return false; }return true;}intMain () {Const CharSzsocketpath[] ="/tmp/test.sock";intIFd = socket (Af_unix, Sock_stream,0);if(IFd <0) {Log_err ("Create Socket Fail:%s", Strerror (errno));return 1; }if(! Connectunixsocket (Szsocketpath, iFd)) {Log_err ("Connectunixsocket Fail");return 1; } log_info ("Connect Success");if(Sig_err = = Signal (sigpipe, Sigpipehandler))//Call the Write function when the connection is interrupted to receive the sigpipe signal{Log_err ("Signal Fail:%s", Strerror (errno));return 1; }Charszcontent[2048]; ssize_t Nwrite =0; while(Cin>> szcontent) {nwrite = write (IFd, szcontent,strlen(szcontent));if(Nwrite <0) {Log_err ("Write Fail:%s", Strerror (errno));return 1; }    }return 0;}

Program Test Results:

Server Side

$./testunixsocketPID:10013| Listening On/tmp/test. SockPID:10013| Connected:client AddrPID:10037| Listening On/tmp/test. SockPID:10013| Read -BYTES:[ALSDKFJLASJDF]PID:10013| Read -BYTES:[ASDFLJASLDFALSKDJF]PID:10013| Read -BYTES:[ALSDJKFASLDFJALSDKFJ]PID:10013| Read inBytes:[asdasdfasdfasdfasdasdflkjsadf]^c

Client Side

$ ./Client PID:10036|Connect SuccessalsdkfjlasjdfasdfljasldfalskdjfalsdjkfasldfjalsdkfjasdasdfasdfasdfasdasdflkjsadfasdfasdffsdPID:10036|SigPipe received          --- Server端退出后对Fd写入,收到SIGPIPE

Cross-process communication using UNIX domain sockets

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.