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;
}
阅读(2886) | 评论(0) | 转发(0) |