1 #include <sys/types.h>
2 #include <sys/wait.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 
8 	int
main(int argc,char * argv[])9 main(int argc, char *argv[])
10 {
11 	int pipefd[2];
12 	pid_t cpid;
13 	char buf;
14 
15 	if (argc != 2) {
16 		fprintf(stderr, "Usage: %s <string>\n", argv[0]);
17 		exit(EXIT_FAILURE);
18 	}
19 
20 	if (pipe(pipefd) == -1) {
21 		perror("pipe");
22 		exit(EXIT_FAILURE);
23 	}
24 
25 	cpid = fork();
26 	if (cpid == -1) {
27 		perror("fork");
28 		exit(EXIT_FAILURE);
29 	}
30 
31 	if (cpid == 0) {    /* Child reads from pipe */
32 		close(pipefd[1]);          /* Close unused write end */
33 		sleep(10);
34 		printf("child: reading...\n");
35 
36 		while (read(pipefd[0], &buf, 1) > 0)
37 			write(STDOUT_FILENO, &buf, 1);
38 		printf("child: done.\n");
39 
40 		write(STDOUT_FILENO, "\n", 1);
41 		close(pipefd[0]);
42 		_exit(EXIT_SUCCESS);
43 
44 	} else {            /* Parent writes argv[1] to pipe */
45 		close(pipefd[0]);          /* Close unused read end */
46 		sleep(5);
47 		printf("parent: writing...\n");
48 		write(pipefd[1], argv[1], strlen(argv[1]));
49 		close(pipefd[1]);          /* Reader will see EOF */
50 		printf("parent: pipe closed\n");
51 		//wait(NULL);                /* Wait for child */
52 		exit(EXIT_SUCCESS);
53 	}
54 }
55 
56