-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path015_unknown_pipe_line.c
54 lines (45 loc) · 1.23 KB
/
015_unknown_pipe_line.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
// Unknown pipeline
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>
int main() {
int pipefd[2];
pid_t pid;
// Create an unnamed pipe
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// Fork a child process
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // Child process
// Write data to the pipe
char message[] = "Hello from the child process!";
if (write(pipefd[1], message, sizeof(message)) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
// Close the write end of the pipe
close(pipefd[1]);
} else { // Parent process
// Read data from the pipe
char message[1024];
int bytesRead = read(pipefd[0], message, sizeof(message));
if (bytesRead == -1) {
perror("read");
exit(EXIT_FAILURE);
}
// Print the data read from the pipe
printf("Received data from child process: %s\n", message);
// Close the read end of the pipe
close(pipefd[0]);
}
// Wait for the child process to finish
waitpid(pid, NULL, 0);
return 0;
}