-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipe.c
More file actions
38 lines (33 loc) · 776 Bytes
/
pipe.c
File metadata and controls
38 lines (33 loc) · 776 Bytes
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
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define READ_BUF_SIZE 80
void exit_with_failure(char *message) {
perror(message);
exit(EXIT_FAILURE);
}
int main(void) {
int n;
int pipe_fd[2];
pid_t pid;
char msg [] = "hello from parent\n";
if (pipe(pipe_fd) < 0)
exit_with_failure("pipe error");
if ((pid = fork()) < 0) {
exit_with_failure("fork error");
} else if (pid > 0) {
// in parent, closing read end of pipe
close(pipe_fd[0]);
write(pipe_fd[1], msg, strlen(msg));
} else {
// in child, closing write end of pipe
close(pipe_fd[1]);
char line[READ_BUF_SIZE];
n = read(pipe_fd[0], line, READ_BUF_SIZE);
write(STDOUT_FILENO, line, n);
}
exit(EXIT_SUCCESS);
}