码迷,mamicode.com
首页 > 其他好文 > 详细

标准管道(popen)

时间:2014-08-23 13:54:00      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   for   ar   2014   

NAME
       popen, pclose - pipe stream to or from a process

SYNOPSIS
       #include <stdio.h>

       FILE *popen(const char *command, const char *type);

       int pclose(FILE *stream);

DESCRIPTION
       The popen() function opens a process by creating a pipe,  forking,  and
       invoking  the shell.  Since a pipe is by definition unidirectional, the
       type argument may specify  only  reading  or  writing,  not  both;  the
       resulting stream is correspondingly read-only or write-only.

       The  command argument is a pointer to a null-terminated string contain-
       ing a shell command line.  This command is passed to /bin/sh using  the
       -c  flag;  interpretation, if any, is performed by the shell. 

RETURN VALUE
       The popen() function returns NULL if the fork(2) or pipe(2) calls fail,
       or if it cannot allocate memory.

       The pclose() function returns -1 if wait4(2) returns an error, or  some
       other error is detected.

popen.c,如下:

/*************************************************************************
    > File Name: popen.c
    > Author: KrisChou
    > Mail:zhoujx0219@163.com 
    > Created Time: Fri 22 Aug 2014 11:07:26 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char buf[1024];
    FILE *fp;
    
    while(memset(buf,0,1024),fgets(buf,1024,stdin) != NULL)
    {
        fp = popen(argv[1],"w");
        fputs(buf,fp);
        pclose(fp);
    }

    return 0;
}

被调用函数reverse.c,如下:

/*************************************************************************
    > File Name: reverse.c
    > Author: KrisChou
    > Mail:zhoujx0219@163.com 
    > Created Time: Sat 23 Aug 2014 11:21:27 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char word[256]; //从标准输入读取字符串
    char buf[256][256],index = 0; //保存从标准输入读取的字符串
    while(memset(word,0,256), scanf("%s",word) != EOF )
    {
        strcpy(buf[index++],word);
    }
    index--;
    while(index >=0 )
    {
        printf("%s ",buf[index]);
        index--;
    }
    printf("\n");
    return 0;
}

运行程序:

[purple@localhost popen]$ gcc popen.c -o main
[purple@localhost popen]$ gcc reverse.c -o reverse
[purple@localhost popen]$ ./main ./reverse
how are you
you are how
baby u r beautiful
beautiful r u baby
[purple@localhost popen]$

按 ctrl+D 退出popen.c中的循环,从而退出程序。

标准管道(popen)

标签:des   style   blog   color   os   io   for   ar   2014   

原文地址:http://www.cnblogs.com/jianxinzhou/p/3930913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!