unix domain socket 进程间通信简析

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\n");
break;
}
buf[recv_size-1] = '\0';
printf("recv buf:%s from client\n", 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\n");
break;
}
buf[read_size-1] = '\0';
printf("send buf: %s\n", buf);
}
}
}


close(sock_fd);


unlink(UNIX_CLI);


return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪游东戴河

你就是这个世界的唯一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值