利用本地套接字,也能夠進程間通訊。c++
本地套接字和有名管道同樣都利用僞文件shell
管道的文件類型是p微信
本地套接字的文件類型是s。網絡
當調用bind函數後,就會生成本地套接字對應的假裝文件socket
srwxr-xr-x 1 ys ys 0 7月 2 10:55 server.socket srwxr-xr-x 1 ys ys 0 7月 2 10:55 client.socket
和網絡套接字不一樣的地方是:函數
struct sockaddr_un{ sun_family;//AF_LOCAL sun_path;//本地套接字對應的假裝文件的名字,能夠加路徑 }
接收端例子:學習
#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(){ int fd = socket(AF_LOCAL, SOCK_STREAM, 0); unlink("server.socket"); struct sockaddr_un serv; strcpy(serv.sun_path, "server.socket"); serv.sun_family = AF_LOCAL; int ret = bind(fd, (struct sockaddr*)&serv, sizeof(serv)); if(ret == -1){ perror("bind error"); exit(1); } listen(fd, 64); struct sockaddr_un cli; socklen_t len; int cfd = accept(fd, (struct sockaddr*)&cli, &len); while(1){ char buf[64]; ret = recv(cfd, buf, sizeof(buf), 0); if(ret == -1){ perror("recv error"); exit(1); } else if(ret == 0){ printf("client closed\n"); close(cfd); } printf("clinet path:%s\n", cli.sun_path); write(STDOUT_FILENO, buf, ret); } close(cfd); close(fd); }
發送端例子:code
#include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(){ int fd = socket(AF_LOCAL, SOCK_STREAM, 0); unlink("client.socket"); struct sockaddr_un cli; strcpy(cli.sun_path, "client.socket"); cli.sun_family = AF_LOCAL; if(bind(fd, (struct sockaddr*)&cli, sizeof(cli)) == -1){ perror("bind cli error"); exit(1); } struct sockaddr_un to; to.sun_family = AF_LOCAL; strcpy(to.sun_path, "server.socket"); int ret = connect(fd, (struct sockaddr*)&to, sizeof(to)); int cnt = 0; while(1){ char buf[64] = {0}; sprintf(buf, "cnt = %d", cnt++); int ret = send(fd, buf, sizeof(buf), 0); if(ret == -1){ perror("send error"); exit(1); } sleep(1); } }