Chinaunix首页 | 论坛 | 博客
  • 博客访问: 292657
  • 博文数量: 52
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 587
  • 用 户 组: 普通用户
  • 注册时间: 2017-03-09 09:24
个人简介

水滴

文章分类

全部博文(52)

文章存档

2021年(3)

2019年(8)

2018年(32)

2017年(9)

我的朋友

分类: LINUX

2019-02-14 15:34:03

1 unix通信
unix通信不经过协议栈处理,效率高
2 源码
path为绑定文件路径:例如'/tmp/ValinkGpsUnix'
int unix_init(char *path)
{
int socketfd = -1;
int ret = 0;
int recvBufSize;
socklen_t socketlen;
struct sockaddr_un socket_addr;


if(NULL == path){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}

//create  socket fd
socketfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(socketfd < 0){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}


unlink(path);
memset(&socket_addr, 0, sizeof(socket_addr));
socket_addr.sun_family = AF_UNIX;
strncpy(socket_addr.sun_path, path, sizeof(socket_addr.sun_path)-1);


//bind fd to socket_addr
ret = bind(socketfd, (struct sockaddr*)&socket_addr, sizeof(socket_addr));
if(ret < 0){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}
    
    
socketlen = sizeof(recvBufSize);
recvBufSize = UNIX_SIZE;
ret = setsockopt(socketfd, SOL_SOCKET, SO_RCVBUF, &recvBufSize, socketlen);
if(ret < 0){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}
    return socketfd;
}


int unix_send(int fd, char *path, unsigned int length, char *data)
{
int res = 0;
int sendlen = length;
char *msgptr = data;
int failurecount =0;
struct sockaddr_un socket_addr;
socklen_t socketlen;


if(NULL == path || NULL == data){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}


socketlen = sizeof(socket_addr);
memset(&socket_addr, 0, sizeof(socket_addr));
socket_addr.sun_family = AF_UNIX;
strncpy(socket_addr.sun_path, path, sizeof(socket_addr.sun_path)-1);


while((sendlen > 0) && (failurecount <= FAILURE_COUNT)){
             res = sendto(fd, (void *)msgptr,  sendlen, 0, (struct sockaddr *)(&socket_addr), socketlen);  
if(res > 0){
sendlen = (length - res);
msgptr += res;
}else{
failurecount ++;
debug(DEBUG_ERROR,"%s[%d]Send retry !!\n", __func__, __LINE__);
continue;
}
}


if((failurecount > FAILURE_COUNT) && (sendlen > 0)){
debug(DEBUG_ERROR, "%s[%d] error\n", __func__, __LINE__);
return -1;
}


return 0;
}

阅读(2829) | 评论(0) | 转发(0) |
0

上一篇:SHA256原理详解

下一篇:ipv6基础

给主人留下些什么吧!~~