在linux下,存在着这样的情况,本地的进程间通信,并且其中一个是服务端,另外的都是客户端。
服务端通过绑定端口,客户端往127.0.0.1的对应端口发送,即可办到,不过这样会浪费一个端口,同时也容易造成安全隐患。
今天发现linux服务端创建socket的时候,协议族用AF_UNIX即可,AF_LOCAL和AF_UNIX的值是一样的。
而AF_UNIX和127.0.0.1回环地址相比,具有哪些好处呢。本人读了下面博客:
Unix domain socket 简介
其中里面讲到UNIX domain socket 用于 IPC 更有效率:不需要经过网络协议栈,不需要打包拆包、计算校验和、维护序号和应答等。本人想当然认为AF_UNIX速度比127.0.0.1更快,为此鄙人进行了实验。
找一个比较大的文件,超过1G大小,然后
1。用AF_UNIX写客户端和服务端,由客户端读取文件,发送给AF_UNIX服务端,然后服务端写文件,看看用AF_UNIX传递一个文件需要多久。
2. 用127.0.0.1写客户端和服务端,由客户端读取文件,发送给127.0.0.1服务端,然后服务端写文件,看看用127.0.0.1传递一个文件需要多久。
废话不多说,直接上代码,先上AF_UNIX的:
AF_UNIX服务端(unixsocketserver.c):
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#define MAXLINE 80
char *socket_path = "/tmp/server.socket";
#define RECV_LEN 1000
int main(void)
{
fd_set readmask, exceptmask;
struct timeval tv;
int maxfd = FD_SETSIZE;
int nready = 0;
FILE *fp = fopen("/tmp/pull_desktop234_copy.flv", "w");
if(fp == NULL)
{
perror("fopen pull_desktop234_copy.flv failed");
goto end;
}
char buf[RECV_LEN + 1];
int readbyte, writebyte;
struct sockaddr_un serun, cliun;
socklen_t cliun_len;
int listenfd, connfd, size;
if ((listenfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
perror("socket error");
exit(1);
}
memset(&serun, 0, sizeof(serun));
serun.sun_family = AF_UNIX;
strcpy(serun.sun_path, socket_path);
size = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path);
unlink(socket_path);
if (bind(listenfd, (struct sockaddr *)&serun, size) < 0) {
perror("bind error");
exit(1);
}
printf("UNIX domain socket bound\n");
if (listen(listenfd, 20) < 0) {
perror("listen error");
exit(1);
}
printf("Accepting connections ...\n");
cliun_len = sizeof(cliun);
if ((connfd = accept(listenfd, (struct sockaddr *)&cliun, &cliun_len)) < 0){
perror("accept error");
goto end;
}
time_t now, endtime;
now = time(NULL);

文章探讨了Linux中使用AF_UNIX(Unixdomainsocket)与127.0.0.1进行进程间通信的效率差异,实验证明AF_UNIX在文件传输速度上通常更快,尤其是在大文件情况下。
最低0.47元/天 解锁文章
744

被折叠的 条评论
为什么被折叠?



