socket unix domain IPC的实例代码
更新时间:2016年12月28日 09:58:37 投稿:jingxian
下面小编就为大家带来一篇socket unix domain IPC的实例代码。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
仅供参考:
服务端:socket->bind->listen->send/recv->close
客户端:socket->bind->connect->send/recv->close
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/un.h>
#include <pthread.h>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <signal.h>
#define filename "test.socket"
void setnonblocking(int fd)
{
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
}
void *client_func(void *arg)
{
sleep(3);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
setnonblocking(fd);
sockaddr_un un;
memset(&un, 0, sizeof(un));
un.sun_family = AF_UNIX;
sprintf(un.sun_path, "file_%d.socket", (int)getpid());
unlink(un.sun_path);
socklen_t len = sizeof(un);
bind(fd, (sockaddr *)&un, sizeof(un));
strcpy(un.sun_path, filename);
int ret = connect(fd, (sockaddr *)&un, len);
if (ret == -1)
{
printf("connect server failed...\n");
close(fd);
return NULL;
}
char buf[256];
memset(buf, 0, sizeof(buf));
strcpy(buf, "hello world");
int n = send(fd, buf, strlen(buf)+1, 0);
printf("send data, %d bytes..\n", n);
sleep(5);
close(fd);
return NULL;
}
int main()
{
unlink(filename);
signal(SIGPIPE, SIG_IGN);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
setnonblocking(fd);
sockaddr_un un;
memset(&un, 0, sizeof(un));
un.sun_family = AF_UNIX;
strcpy(un.sun_path, filename);
bind(fd, (sockaddr *)&un, sizeof(un));
listen(fd, 100);
pthread_t pid;
pthread_create(&pid, NULL, client_func, NULL);
sockaddr_un uu;
socklen_t len = sizeof(uu);
while (true)
{
memset(&uu, 0, len);
int newfd = accept(fd, (sockaddr *)&uu, &len);
if (newfd != -1)
{
setnonblocking(newfd);
printf("newfd = %d, path = %s\n", newfd, uu.sun_path);
char buf[512];
memset(buf, 0, sizeof(buf));
int n = recv(newfd, buf, 512,0);
printf("recv %d bytes, contents is %s\n", n, buf);
}
usleep(100000);
}
close(fd);
return 0;
}
以上就是小编为大家带来的socket unix domain IPC的实例代码全部内容了,希望大家多多支持脚本之家~
相关文章
ubuntu16.10安装docker17.03.0-ce并配置国内源和加速器
这篇文章主要介绍了ubuntu16.10安装docker17.03.0-ce并配置国内源和加速器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05
redhat Server release 5.2 安装配置简明教程
系统安装:系统安装采用光盘安装,以前一直从USB移动硬盘安装,前几天心血来潮,刻成了DVD,以示严肃和一切从头开始,呵呵。2009-08-08


最新评论