-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathsockpair.cpp
More file actions
62 lines (54 loc) · 1.07 KB
/
sockpair.cpp
File metadata and controls
62 lines (54 loc) · 1.07 KB
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
//
// Created by jxq on 19-8-10.
//
// socket编程 17
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0);
int main(int argc, char** argv)
{
int fd[2];
int r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
if (r < 0)
{
ERR_EXIT("socketpair");
}
pid_t pid = fork();
if (pid == 0)
{
int val = 0;
close(fd[0]);
while (1)
{
sleep(1);
++val;
printf("sending data: %d\n", val);
write(fd[1], &val, sizeof val);
read(fd[1], &val, sizeof val);
printf("recver data: %d\n", val);
}
}
else
{
close(fd[1]);
int val;
while (1)
{
read(fd[0], &val, sizeof val);
val++;
write(fd[0], &val, sizeof val);
}
}
return 0;
}