UNIX Domain Socket IPC, domainipc

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

UNIX Domain Socket IPC, domainipc
Directory

  • Directory
  • Overview
  • Socket function usage
    • Struct sockaddr_un
    • Socket
    • Bind
    • Listen
    • Accept
    • Connect
  • Socket IPC instance
    • Server
    • Client
    • Running result

Overview

The socket API was originally designed for network communication, but later an IPC Mechanism was developed on the socket framework, namely the UNIX Domain Socket.

Although the network socket can also be used for inter-process communication between the same host (through the loopback address 127.0.0.1), the UNIX Domain Socket is more efficient for IPC:

  • No need to go through the network protocol stack.
  • No need to package or unpack
  • Checksum is not required
  • No need to maintain serial numbers and responses

This is because the IPC Mechanism is essentially reliable communication, and the network protocol is designed for unreliable communication. UNIX Domain Socket also provides two API interfaces: Stream-oriented and data packet-oriented, such as TCP and UDP. However, the stream-oriented UNIX Domain Socket is also reliable, and messages are neither lost nor disordered.

The process of using UNIX Domain Socket is very similar to that of network socket. You must first call socket () to create a socket file descriptor. The address family is specified as AF_UNIX, And the type can be SOCK_STREAM or SOCK_DGRAM, the protocol parameter is still set to 0.

The most obvious difference between UNIX Domain Socket and network socket programming is that the address format is different. It is represented by the addr_un struct. The socket address of network programming is the IP address and port number, the UNIX Domain Socket address is the path of a socket-type file in the file system. This socket file is created by the bind () call. If the file already exists when bind () is called, then the bind () error is returned.

Socket function usage

Next, we will explain the main functions used in UNIX Domain Socket programming.

Struct sockaddr_un

The address struct used by UNIX Domain Socket is defined as follows:

#define UNIX_PATH_MAX 108struct sockaddr_un {    sa_family_t sun_family; /* AF_UNIX */    char sun_path[UNIX_PATH_MAX]; /* pathname */};
Socket ()
#include <sys/types.h>#include <sys/socket.h>int socket(int domain, int type, int protocol);

Parameters are defined as follows:

After the socket () function is called, the file descriptor is returned. If the socket () function fails,-1 is returned.

Bind ()
#include <sys/types.h>#include <sys/socket.h>int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Bind () allocates an address for the socket. After a socket () is used to create a socket, only the protocol used by the socket () is granted, but no address is allocated. Before accepting connections from other hosts, bind () must be called to allocate the socket address.

Parameters are defined as follows:

Listen ()
#include <sys/types.h>#include <sys/socket.h>int listen(int sockfd, int backlog);

After the socket is bound to an address, call the listen () function to start listening for connection requests. However, this can only be used when reliable data streams are guaranteed, such as SOCK_STREAM.

Parameters are defined as follows:

If the listener is successful, 0 is returned. Otherwise,-1 is returned.

Accept ()
#include <sys/types.h>#include <sys/socket.h>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

When an application listens to Data Stream-oriented connections from other hosts, it is notified through events (such as UNIX select () system calls. The connection must be initialized using the accept () function. Accept () creates a new socket for each connection and removes the connection from the listener queue.

Parameters are defined as follows:

Accpet returns a new socket descriptor successfully, and-1 is returned if an error occurs. Further communication must pass through this socket.

Connect ()
#include <sys/types.h>#include <sys/socket.h>int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

The connect () System Call sets a connection for a socket. The parameters include the file descriptor and host address.

Socket IPC instance

Next, we will briefly implement a reference instance for communication between processes through UNIX Domain Socket.

Server
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <stddef.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/un.h>#include <unistd.h>#define QLEN 8char *socket_path="wzy.socket";int main(int argc, char **argv){    int fd, clifd, n;    struct sockaddr_un un;    char buf[100];    if (argc > 1) socket_path = argv[1];    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {        perror("socket error");        exit(1);    }    memset(&un, 0, sizeof(un));    un.sun_family = AF_UNIX;    strncpy(un.sun_path, socket_path, sizeof(un.sun_path) - 1);    unlink(socket_path);    if (bind(fd, (struct sockaddr *) &un, sizeof(un)) < 0) {        perror("bind error");        exit(1);    }    printf("UNIX Domain Socket bound\n");    memset(&buf, 0, sizeof(buf));    if (listen(fd, QLEN) < 0) {        perror("listen error");        exit(1);    }    while (1) {        if ((clifd = accept(fd, NULL, NULL)) == -1) {            perror("accpet error");            continue;        }        while ((n = read(clifd, buf, sizeof(buf))) > 0) {            printf("read %d bytes: %s\n", n, buf);        }        if (n == -1) {            exit(-1);        } else if (n == 0) {            printf("END\n");            close(clifd);        }    }    return 0;}
Client
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <stddef.h>#include <sys/types.h>#include <sys/socket.h>#include <sys/un.h>#include <unistd.h>char *socket_path="wzy.socket";int main(int argc, char **argv){    int fd;    struct sockaddr_un un;    char buf[100];    if (argc > 1) socket_path = argv[1];    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {        perror("socket error");        exit(1);    }    memset(&un, 0, sizeof(un));    un.sun_family = AF_UNIX;    strncpy(un.sun_path, socket_path, sizeof(un.sun_path) - 1);    if (connect(fd, (struct sockaddr *) &un, sizeof(un)) < 0) {        perror("connect error");        exit(-1);    }    while (scanf("%s", buf) != EOF) {        if (write(fd, buf, sizeof(buf)) < 0) {            perror("write error");            exit(-1);        }    }    return 0;}
Running result

Server listens to the data sent by the client:

The data uploaded by the client is as follows:

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.