-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe_width.c
125 lines (103 loc) · 2.23 KB
/
pipe_width.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
void *wait_thread(void *arg)
{
int status;
int ret = wait(&status);
if (ret == -1) {
perror("wait");
exit(EXIT_FAILURE);
}
printf("child process %d exit with %d\n", ret, status);
exit(0);
}
int write_pipe(int fd, int n, int size)
{
char *p = malloc(size);
if (p == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
int i;
for (i = 0; i < n; i++) {
int ret = write(fd, p, size);
if (ret == -1) {
perror("write");
exit(EXIT_FAILURE);
}
}
free(p);
return 0;
}
int read_pipe(int fd, int n, int size)
{
char *p = malloc(size);
if (p == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
int i;
for (i = 0; i < n; i++) {
int ret = read(fd, p, size);
if (ret == -1) {
perror("read");
exit(EXIT_FAILURE);
}
}
free(p);
return 0;
}
int main(int argc, char *argv[])
{
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
long n = atol(argv[1]);
long size = atol(argv[2]);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid != 0) {
struct timespec start, end;
pthread_t tid;
close(pipefd[0]);
pthread_create(&tid, NULL, wait_thread, NULL);
clock_gettime(CLOCK_MONOTONIC, &start);
write_pipe(pipefd[1], n, size);
clock_gettime(CLOCK_MONOTONIC, &end);
close(pipefd[1]);
int second = end.tv_sec - start.tv_sec;
long nsecond = end.tv_nsec - start.tv_nsec;
if (nsecond < 0) {
second -= 1;
nsecond += 1000000000L;
}
double width = (double)n * size / 1024 / 1024 / (second + (double)(nsecond / 1000000000.0));
printf("write time: %d.%03d, width %d M\n", second, (int)(nsecond / 1000000), (int)width);
usleep(10000000);
} else {
struct timespec start, end;
close(pipefd[1]);
clock_gettime(CLOCK_MONOTONIC, &start);
read_pipe(pipefd[0], n, size);
clock_gettime(CLOCK_MONOTONIC, &end);
close(pipefd[0]);
int second = end.tv_sec - start.tv_sec;
long nsecond = end.tv_nsec - start.tv_nsec;
if (nsecond < 0) {
second -= 1;
nsecond += 1000000000L;
}
printf("read time: %d.%03d\n", second, (int)(nsecond / 1000000));
}
return 0;
}