blob: 4ec9866be54cc0230ed492a4937256674a32e015 (
plain)
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
|
/* fpipe.c
*
* Parent writing to child
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
#define MAX_LINE 80
int main(int argc, char **argv)
{
pid_t pid;
int stat_loc;
int pfds[2];
int ret;
char buf[MAX_LINE+1];
const char *testbuf = { "I'm a parent and I'm writing to you" };
if (pipe(pfds) == 0)
{
pid = fork();
if (pid == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (!pid)
{
close(pfds[1]); /* child will not be writing anything */
ret = read(pfds[0], buf, MAX_LINE);
buf[ret] = 0;
printf("Child read: %s\n", buf);
}
else
{
close(pfds[0]); /* parent will not be reading anything */
ret = write(pfds[1], testbuf, strlen(testbuf));
ret = waitpid(pid, &stat_loc, WCONTINUED);
}
}
else
{
perror("pipe");
exit(EXIT_FAILURE);
}
close(pfds[0]);
close(pfds[1]);
return 0;
}
|