Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359780
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: LINUX

2011-04-21 11:55:37

  1. #include <unistd.h>
  2. int pipe(int filedes[2]);    //成功:0 出错:-1

  1. #include <stdio.h>
  2. #include <unistd.h>

  3. int
  4. main(void)
  5. {
  6.         int n;
  7.         int fd[2];
  8.         pid_t pid;
  9.         char line[128];

  10.         if (pipe(fd) < 0) {
  11.                 printf("pipe error\n");
  12.                 return (-1);
  13.         }
  14.         if ((pid = fork()) < 0) {
  15.                 printf("fork error\n");
  16.                 return (-1);
  17.         } else if (pid > 0) {
  18.                         close(fd[0]);
  19.                         write(fd[1], "hello world\n" , 12);
  20.                 } else {
  21.                         close(fd[1]);
  22.                         n = read(fd[0], line, 128);
  23.                         write(1, line, n);
  24.                 }

  25.         return (0);
  26. }

  1. #include <stdio.h>
  2. FILE *popen(const char *cmdstring, const char *type);   //成功:文件指针  出错:NULL

  3. int pclose(FILE *fp);    //成功:终止状态   出错:-1

  1. #include <stdio.h>

  2. int
  3. main(void)
  4. {
  5.         char buf[128];
  6.         FILE *fp = popen("ls", "r");
  7.         if (NULL == fp) {
  8.                 printf("popen error\n");
  9.                 return (-1);
  10.         }

  11.         while (fgets(buf, 128, fp) != NULL) {
  12.                 if (fputs(buf, stdout) == EOF) {
  13.                         printf("over\n");
  14.                 }
  15.         }

  16.         if (pclose(fp) == -1) {
  17.                 printf("pclose error\n");
  18.                 return (-1);
  19.         }

  20.         FILE *fp2 = popen("cat", "w");
  21.         if (NULL == fp2) {
  22.                 printf("popen error\n");
  23.                 return (-1);
  24.         }
  25.         fputs("hello\n", fp2);

  26.         if (pclose(fp2) == -1) {
  27.                 printf("pclose error\n");
  28.                 return (-1);
  29.         }

  30.         return (0);
  31. }



阅读(1228) | 评论(0) | 转发(0) |
0

上一篇:堆排序

下一篇:string II Iterator

给主人留下些什么吧!~~