小知识:socket unix domain IPC的实例代码

仅供参考:

服务端:socket->bind->listen->send/recv->close

客户端:socket->bind->connect->send/recv->close

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#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的实例代码全部内容了,希望大家多多支持服务器之家~

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:浅谈linux下的串口通讯开发

2023-4-12 4:09:05

建站知识

小知识:nginx keepalive的具体使用

2023-4-12 4:19:45

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索