Unix domain socket
原文:https://www.cnblogs.com/sparkdev/p/8359028.html
UNIX Domain Socket是在socket架构上发展起来的用于同一台主机的进程间通讯(IPC),它不需要经过网络协议栈,不需要打包拆包、计算校验和、维护序号和应答等,只是将应用层数据从一个进程拷贝到另一个进程。UNIX Domain Socket有SOCK_DGRAM或SOCK_STREAM两种工作模式,类似于UDP和TCP,但是面向消息的UNIX Domain Socket也是可靠的,消息既不会丢失也不会顺序错乱。
#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 = "server.socket"; int main(void) { struct sockaddr_un serun, cliun; socklen_t cliun_len; int listenfd, connfd, size; char buf[MAXLINE]; int i, n; 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"); while(1) { cliun_len = sizeof(cliun); if ((connfd = accept(listenfd, (struct sockaddr *)&cliun, &cliun_len)) < 0){ perror("accept error"); continue; } while(1) { n = read(connfd, buf, sizeof(buf)); if (n < 0) { perror("read error"); break; } else if(n == 0) { printf("EOF\n"); break; } printf("received: %s", buf); for(i = 0; i < n; i++) { buf[i] = toupper(buf[i]); } write(connfd, buf, n); } close(connfd); } close(listenfd); return 0; } |
#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> #define MAXLINE 80 char *server_path = "server.socket"; int main() { struct sockaddr_un serun; int len; char buf[100]; int sockfd, n; if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){ perror("client socket error"); exit(1); } memset(&serun, 0, sizeof(serun)); serun.sun_family = AF_UNIX; strcpy(serun.sun_path, server_path); len = offsetof(struct sockaddr_un, sun_path) + strlen(serun.sun_path); if (connect(sockfd, (struct sockaddr *)&serun, len) < 0){ perror("connect error"); exit(1); } while(fgets(buf, MAXLINE, stdin) != NULL) { write(sockfd, buf, strlen(buf)); n = read(sockfd, buf, MAXLINE); if ( n < 0 ) { printf("the other side has been closed.\n"); }else { write(STDOUT_FILENO, buf, n); } } close(sockfd); return 0; } |
原文地址:https://www.cnblogs.com/sunnypoem/p/11782450.html