Internet高级编程作业:用pipe, fork实现popen

/*  myopen.c -  用pipe, fork实现popen
 *      FILE *popen(const char *command, const char *type);
 *        姓名:林丹,学号:06S037012,日期:2006-10-17
 
*/

#include    
< stdio.h >
#include    
< signal.h >
#include    
< unistd.h >


FILE 
* mypopen( const   char   * command,  const   char   * mode);
int  execl( const   char   * path,  const   char   * arg, ...);

// #define AT_WINDOWS
#ifdef AT_WINDOWS
#define  pid_t int
int  pipe( int  filedes[ 2 ]) {return 0;}
pid_t fork(
void ) {return 0;}
#endif

int  main( int  len,  char **  args)
{
    FILE    
*fp;
    
char    buf[BUFSIZ];
    
    
/*test 在程序中获得cat /etc/passwd的输出*/
    fp 
= (FILE*)mypopen("cat /etc/passwd","r");
    
while( fgets(buf, BUFSIZ,fp) != NULL)
        fputs(buf, stdout);
    
return 0;
}



FILE 
* mypopen( const   char   * command,  const   char   * mode)
{
    
int    fd[2], pid;        /* the pipe and the process    */
    FILE     
*fp;        
    
int    parent_end, child_end;    /* of pipe             */

    
if ( *mode == 'r' ){        /* figure out direction        */
        parent_end 
= STDIN_FILENO;
        child_end 
= STDOUT_FILENO ;
    }
 else if ( *mode == 'w' ){
        parent_end 
= STDOUT_FILENO;
               child_end 
= STDIN_FILENO ;
    }
 else return NULL ;

    
if ( pipe(fd) == -1 )             /* get a pipe        */
        
return NULL;
    
if ( (pid = fork()) == -1 ){        /* failed create child process    */
        close(fd[
0]);                    /* */
        close(fd[
1]);
        
return NULL;
    }

        
/* --------------- child code here --------------------- */
    
/*   need to redirect stdin or stdout then exec the cmd     */
    
else if(0 == pid){
        
if ( close(fd[parent_end]) == -1 )    /* close the other end    */
            exit(
1);            /* do NOT return    */

        
if ( dup2(fd[child_end], child_end) == -1 )
            exit(
1);

        
if ( close(fd[child_end]) == -1 )    /* done with this one    */
            exit(
1);
                            
/* all set to run cmd    */
        execl( 
"/bin/sh""sh""-c", command, NULL );
        exit(
1);
    }


    
/* --------------- parent code here ------------------- */
    
/*   need to close one end and fdopen other end        */

    
else{    
        
if (close( fd[child_end] ) == -1 )
            
return NULL;
        
return (FILE *)fdopen( fd[parent_end] , mode);    /* creeat a stream */
    }



}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值