c/c++ linux 进程间通信系列2,使用UNIX_SOCKET

时间:2023-03-08 22:11:08
c/c++ linux 进程间通信系列2,使用UNIX_SOCKET

linux 进程间通信系列2,使用UNIX_SOCKET

1,使用stream,实现进程间通信

2,使用DGRAM,实现进程间通信

关键点:使用一个临时的文件,进行信息的互传。

  s_un.sun_family = AF_UNIX;
strcpy(s_un.sun_path, "/tmp/afunix_text");

使用stream,server端:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h> #define FILEPATH "/tmp/afunix_text" int main(){
int s0, sock;
sockaddr_un s_un;
sockaddr_un s_un_accept;
socklen_t addrlen; s0 = socket(AF_UNIX, SOCK_STREAM, 0);
if(s0 < 0){
perror("socket");
return 1;
} s_un.sun_family = AF_UNIX;
strcpy(s_un.sun_path, FILEPATH); if(bind(s0, (sockaddr*)&s_un, sizeof(s_un)) != 0){
perror("bind");
return 1;
} if(listen(s0, 5) != 0){
perror("listen");
return 1;
} addrlen = sizeof(s_un_accept);
sock = accept(s0, (sockaddr*)&s_un_accept, &addrlen);
if(sock < 0){
perror("accept");
return 1;
} printf("after accept\n"); write(sock, "the msg is send from server", 27);
close(sock);
close(s0); unlink(FILEPATH); return 0;
}

github源代码

使用stream,client端:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h> int main(){
int sock;
sockaddr_un s_un;
int n;
char buf[128]; sock = socket(AF_UNIX, SOCK_STREAM, 0);
if(sock < 0){
perror("socket");
return 1;
} s_un.sun_family = AF_UNIX;
strcpy(s_un.sun_path, "/tmp/afunix_text"); if(connect(sock, (sockaddr*)&s_un, sizeof(s_un)) != 0){
perror("connect");
return 1;
}
printf("after connect\n");
memset(buf, 0, sizeof(buf));
n = read(sock, buf, sizeof(buf));
if(n < 0){
perror("read");
return 1;
} printf("%s\n", buf);
close(sock);
return 0;
}

github源代码

使用dgram,发送端:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h> int main(){
int sock;
sockaddr_un addr;
socklen_t addrlen; sock = socket(AF_UNIX, SOCK_DGRAM, 0);
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "/tmp/afu_dgram"); int n = sendto(sock, "HELLO\n", 6, 0, (sockaddr*)&addr, sizeof(addr));
printf("send data\n");
close(sock);
return 0;
}

github源代码

使用dgram,接收端:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h> int main(){
int sock;
sockaddr_un addr;
socklen_t addrlen;
char buf[1024];
int n; sock = socket(AF_UNIX, SOCK_DGRAM, 0); addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "/tmp/afu_dgram"); bind(sock, (sockaddr*)&addr, sizeof(addr)); while(1){
memset(buf, 0, sizeof(buf));
n = recv(sock, buf, sizeof(buf) - 1, 0);
printf("recv:%s\n", buf);
} close(sock);
return 0;
}

github源代码

c/c++ 学习互助QQ群:877684253

c/c++ linux 进程间通信系列2,使用UNIX_SOCKET

本人微信:xiaoshitou5854