目錄表

*Advanced IPC

0x00 Outline


0x01 Introduction

前面幾個章節已經討論過了多種 IPC,包括 pipe 和 socket,這個章節則聚焦在 UNIX domain sockets

我們可以在 processes 間傳遞開啟的 file descriptors

server 可以藉由名稱關聯到 file descriptors

clients 也可使用這些名稱去連線到 servers


0x02 UNIX domain socket

UNIX domain socket

Unnamed UNIX domain sockets

#include <sys/socket.h>
 
int socketpair(int domain, int type, int protocol, int sockfd[2]);
/* Returns: zero if success, or -1 on error */
int s_pipe(int fd[2])
{
    return(socketpair(AF_UNIX, SOCK_STREAM, 0, fd));
}

Naming UNIX domain sockets

/* The sockaddr_un structure (on Linux and Solaris) */
struct sockaddr_un
{
    sa_family_t sun_family;   /* AF_UNIX */
    char sun_path[108];       /* pathname */
};
 
/* The sockaddr_un structure (on BSD and Mac OS X) */
struct sockaddr_un
{
    unsigned char sun_len;    /* length including null */
    sa_family_t sun_family;   /* AF_UNIX */
    char sun_path[108];       /* pathname */
};

Bind a UNIX domain socket

int main(void)
{
    int fd, size;
    struct sockaddr_un un;
 
    un.sun_family = AF_UNIX;
    strcpy(un.sun_path, "foo.socket");
 
    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
    {
        err_sys("socket failed");
    }
 
    size = offsetof(struct sockaddr_un, sun_path)+ strlen(un.sun_path);
 
    if (bind(fd, (struct sockaddr *)&un, size) < 0)
    {
        err_sys("bind failed");
    }
 
    printf("UNIX domain socket bound\n");
    exit(0);
}

Unique Connections


0x03 Passing File Descriptors