Chinaunix首页 | 论坛 | 博客
  • 博客访问: 171419
  • 博文数量: 44
  • 博客积分: 2762
  • 博客等级: 少校
  • 技术积分: 520
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-04 19:19
文章分类
文章存档

2011年(28)

2010年(16)

我的朋友

分类: LINUX

2010-10-14 16:45:04

看代码




1#include <sys/wait.h>
 2#include <stdio.h>
 3#include <stdlib.h>
 4#include <unistd.h>
 5#include <string.h>
 6
 7int
 8main(int argc, char *argv[])
 9{
10 int pipefd[2];
11 pid_t cpid;
12 char buf;
13
14 if (argc != 2) {
15 fprintf(stderr, "Usage: %s \n", argv[0]);
16 exit(EXIT_FAILURE);
17 }
18
19 if (pipe(pipefd) == -1) {
20 perror("pipe");
21 exit(EXIT_FAILURE);
22 }
23
24 cpid = fork();
25 if (cpid == -1) {
26 perror("fork");
27 exit(EXIT_FAILURE);
28 }
29
30 if (cpid == 0) { /* 从子进程的buf里读入数据*/
31 close(pipefd[1]); /* 不用的write侧关闭 */
32
33 while (read(pipefd[0], &buf, 1) > 0)
34 write(STDOUT_FILENO, &buf, 1);  //是一个标准输出,相当于printf("%s",&buf)
35
36 write(STDOUT_FILENO, "\n", 1);
37 close(pipefd[0]);
38 _exit(EXIT_SUCCESS);
39
40 } else { /* 父进程从argv[1]中读入写入 */
41 close(pipefd[0]); /* 不用的read侧的关闭 */
42 write(pipefd[1], argv[1], strlen(argv[1]));
43 close(pipefd[1]);
44 wait(NULL); /* 等待子进程*/
45 exit(EXIT_SUCCESS);
46 }
47}


结果

1diga@diga-desktop:~/test$ gcc -o pipe1 pipe1.c
2diga@diga-desktop:~/test$ ./pipe1
3Usage: ./pipe1 <string>
4diga@diga-desktop:~/test$ ./pipe1 chenzhonghua
5chenzhonghua
6diga@diga-desktop:~/test$


阅读(811) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~