Chinaunix首页 | 论坛 | 博客
  • 博客访问: 437618
  • 博文数量: 113
  • 博客积分: 446
  • 博客等级: 下士
  • 技术积分: 1229
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-09 16:01
个人简介

Let's go!!!!!

文章分类

全部博文(113)

文章存档

2019年(5)

2018年(4)

2017年(9)

2016年(5)

2015年(39)

2014年(6)

2013年(28)

2012年(17)

分类: LINUX

2012-12-09 16:30:36

FILE *popen ( char *command, char *type)
popen()函数首先调用pipe()函数建立一个管道,然后它用fork()函数建立一个子进程,
运行一个shell 环境,然后在这个shell 环境中运行"command"参数指定的程序。数据在管道
中流向由"type"参数控制。这个参数可以是"r"或者"w",分别代表读和写。需要注意的是,
"r"和"w"两个参数不能同时使用!
注意:管道是在 pclose() 的时候执行 popen() 创建的脚本命令!!!
#include
#include
#include
#define MAX 5

int main(void)
{
        int cntr;
        FILE *pipe_fp;
        char *strings[MAX] = { "roy", "zixia", "gouki","supper", "mmwan"};
        if (( pipe_fp = popen("sort  -r", "w")) == NULL)
        {
                perror("popen");
                exit(1);
        }
        for(cntr=0; cntr        {
                fputs(strings[cntr], pipe_fp);
                fputc('\n', pipe_fp);
        }

        pclose(pipe_fp);
        return(0);
}

结果:
gouki
mmwan
roy
supper
zixia

#include
#include
#include
int main(void)
{
        FILE *pipein_fp, *pipeout_fp;
        char readbuf[50];

        if (( pipein_fp = popen("ls", "r")) == NULL)
        {
            perror("popen");
            exit(1);
        }

        if (( pipeout_fp = popen("sort", "w")) == NULL)
        {
            perror("popen");
            exit(1);
        }

        while(fgets(readbuf, 80, pipein_fp))
          fputs(readbuf, pipeout_fp);

        pclose(pipein_fp);
        pclose(pipeout_fp);
        return(0);
}
结果:
a.out
cscope.in.out
cscope.out
cscope.po.out
library
pthread.c
tags
test
test.c
打印出程序所在目录中的所有文件。

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