Linux系统有多种进程间通信方式,如信号、消息队列、管道等,socket是其中一种,socket使用unix domain 模式进行进程间通信
//服务端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define UNIX_SERV "/tmp/unix_serv" //文件路径名
int main(void)
{
int sock_fd;
struct sockaddr_un serv;
struct sockaddr_un cli;
int ret;
socklen_t serv_len;
sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0); //采用数据报协议
if(sock_fd < 0)
{
perror("fail to socket");
}
unlink(UNIX_SERV); //若文件 存在,则删除
memset(&serv, 0, sizeof(serv));
serv.sun_family = AF_UNIX; //Unix
strncpy(serv.sun_path, UNIX_SERV, sizeof(serv.sun_path)-1); //拷贝文件名
serv_len = sizeof(serv);
ret = bind(sock_fd, (struct sockaddr *)&serv, serv_len); //服务器需要绑定
if(ret == -1)
{
perror("fail to bind");
}
int recv_size;
char buf[1024];
socklen_t cli_len;
memset(&cli, 0, sizeof(cli));
cli_len = sizeof(cli);
while(1)
{
recv_size = recvfrom(sock_fd, buf, sizeof(buf), 0,
(struct sockaddr *)&cli, &cli_len);
if(recv_size > 0)
{
if(strncmp(buf, "exit", strlen("exit") ) == 0)
{
printf("client exit
");
break;
}
buf[recv_size-1] = ' ';
printf("recv buf:%s from client
", buf);
}
}
close(sock_fd);
unlink(UNIX_SERV);
return 0;
}
//客户端代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define UNIX_SERV "/tmp/unix_serv" //服务端文件名
//注:客户端代码可以不绑定地址,如不绑定,则不需要客户端文件名;绑定客户端会生成客户端文件
#define UNIX_CLI "/tmp/unix_cli" //客户端文件名
int main(void)
{
int sock_fd;
struct sockaddr_un serv;
struct sockaddr_un cli;
int ret;
socklen_t serv_len;
socklen_t cli_len;
sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(sock_fd < 0)
{
perror("fail to socket");
}
unlink(UNIX_CLI);
memset(&cli, 0, sizeof(cli));
memset(&serv, 0, sizeof(serv));
cli_len = sizeof(cli);
cli.sun_family = AF_UNIX;
strncpy(cli.sun_path, UNIX_CLI, sizeof(cli.sun_path)-1);
serv_len = sizeof(serv);
serv.sun_family = AF_UNIX;
strncpy(serv.sun_path, UNIX_SERV, sizeof(serv.sun_path)-1);
ret = bind(sock_fd, (struct sockaddr *)&cli, cli_len);
if(ret == -1)
{
perror("fail to bind");
}
int read_size;
int send_size;
char buf[1024];
while(1)
{
read_size = read(STDIN_FILENO, buf, sizeof(buf));
if(read_size > 0)
{
send_size = sendto(sock_fd, buf, read_size, 0,
(struct sockaddr *)&serv, serv_len);
if(serv_len > 0)
{
if(strncmp(buf, "exit", 4) == 0)
{
printf("client exit
");
break;
}
buf[read_size-1] = ' ';
printf("send buf: %s
", buf);
}
}
}
close(sock_fd);
unlink(UNIX_CLI);
return 0;
}