套接字常用的是网络间不同主机间的通信外,但是呢,它也可以实现同一主机的不同进程间的通信,且建立的通信是双向的通信,即本地socket通信。
执行flow如下:
client端code client.c如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
struct data_buf{
int data1;
int data2;
};
int socket_init()
{
int ret;
int socket_fd;
static struct sockaddr_un client_addr;
//creat socket
socket_fd=socket(PF_UNIX,SOCK_STREAM,0);
if(socket_fd<0)
{
perror("fail");
return -1;
}
client_addr.sun_family=AF_UNIX;
strmcpy(client_addr.sun_path,CAN_SERVICE);
ret=connect(socket_fd,(struct sockaddr*)&client_addr,sizeof(client_addr));
if(ret==-1)
{
perror("cannot connect server");
close(socket_fd);
return -1;
}
}
int socket_recv()
{
}
int socket_send()
{
}
int socket_close()
{
}
int main()
{
while()
return 0;
}
server端 server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
struct data_buf{
int data1;
int data2;
};
int socket_init()
{
int ret;
int socket_fd;
static struct sockaddr_un server_addr;
//creat socket
socket_fd=socket(PF_UNIX,SOCK_STREAM,0);
if(socket_fd<0)
{
perror("fail");
return -1;
}
client_addr.sun_family=AF_UNIX;
strmcpy(server_addr.sun_path,CAN_SERVICE);
ret=connect(socket_fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(ret==-1)
{
perror("cannot connect server");
close(socket_fd);
return -1;
}
}
int socket_recv()
{
}
int socket_send()
{
}
int socket_close()
{
}
int main()
{
while()
return 0;
}
原文:https://www.cnblogs.com/xinghuo123/p/12797944.html