1: /*
2: @@
3: Author: JustinZhang
4: Email: uestczhangchao@gmail.com
5: Time: 2012-9-1 23:32:22
6: desc: Example from man, write by hand, test under ubuntu gcc.
7: For the purpose of reviewing pipe.
8: @@
9: */
10:
11: #include <sys/wait.h>
12: #include <stdio.h>
13: #include <stdlib.h>
14: #include <unistd.h>
15: #include <string.h>
16: int main(int argc, char *argv[])
17: {
18: int pipefd[2];
19: pid_t cpid;
20: char buf;
21: if(argc !=2)
22: {
23: fprintf(stderr, "Usage:%s <string>\n",argv[0]);
24: exit(EXIT_FAILURE);
25: }
26: if(pipe(pipefd)==-1)
27: {
28: perror("pipe");
29: exit(EXIT_FAILURE);
30: }
31: cpid = fork();
32: if(cpid == -1)
33: {
34: perror("fork");
35: exit(EXIT_FAILURE);
36: }
37: /*return from child*/
38: if(cpid==0)
39: {
40: /*close the write side of pipe*/
41: close(pipefd[1]);
42: while(read(pipefd[0], &buf, 1)>0)
43: {
44: write(STDOUT_FILENO, &buf, 1);
45: }
46: write(STDOUT_FILENO, "\n", 1);
47: close(pipefd[0]);
48: _exit(EXIT_SUCCESS);
49: }
50: else /*return from parent, write arg[1] to pipe*/
51: {
52: close(pipefd[0]);
53: write(pipefd[1],argv[1],strlen(argv[1]));
54: close(pipefd[1]);
55: wait(NULL);
56: exit(EXIT_SUCCESS);
57: }
58: return 0;
59: }