-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork_pipe_example.c
More file actions
87 lines (73 loc) · 1.77 KB
/
fork_pipe_example.c
File metadata and controls
87 lines (73 loc) · 1.77 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
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
// TO BUILD: cc -g -o <output> -DLIB [-DDIAG] imfs.c fork_pipe_example.c
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "imfs.h"
#define BUF_SIZE 64
#define TOTAL_WRITES 10
int
main()
{
imfs_init();
int pipefd[2];
int pipefd_child[2];
pid_t pid;
char write_buf[BUF_SIZE];
char read_buf[BUF_SIZE];
ssize_t bytes_written, bytes_read;
int i;
if (imfs_pipe(0, pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Pre fork i.g. This copying is handled by lind.
imfs_copy_fd_tables(0, 1);
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// Reader
imfs_close(1, pipefd[1]);
int total_bytes_read = 0;
for (i = 0; i < TOTAL_WRITES; i++) {
size_t expected = strlen("Message #NN: Hello from writer!") + 1;
bytes_read = imfs_read(1, pipefd[0], read_buf, expected);
if (bytes_read == -1) {
perror("read");
exit(1);
} else if (bytes_read == 0) {
fprintf(stderr, "Unexpected EOF\n");
exit(1);
}
printf("Child received: %s\n", read_buf);
total_bytes_read += bytes_read;
}
imfs_close(1, pipefd[0]);
printf("Child done reading %d bytes\n", total_bytes_read);
exit(0);
} else {
// Writer
imfs_close(0, pipefd[0]);
size_t total_written = 0;
for (i = 0; i < TOTAL_WRITES; i++) {
snprintf(write_buf, BUF_SIZE, "Message #%02d: Hello from writer!", i + 1);
size_t len = strlen(write_buf) + 1;
bytes_written = imfs_write(0, pipefd[1], write_buf, len);
if (bytes_written == -1) {
perror("write");
exit(1);
}
total_written += bytes_written;
printf("Parent sent: %s\n", write_buf);
sleep(1);
}
imfs_close(0, pipefd[1]);
printf("Parent wrote %d bytes\n", total_written);
wait(NULL);
exit(0);
}
}