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

#define R    (0)
#define W    (1)

int popen2(char *command,int *fd_r,int *fd_w)
{
int    pipe_c2p[2],pipe_p2c[2];
int    pid;

    /* 2つのパイプの作成 */
    if(pipe(pipe_c2p)<0){
        perror("popen2");
        return(-1);
    }
    if(pipe(pipe_p2c)<0){
        perror("popen2");
        close(pipe_c2p[R]);
        close(pipe_c2p[W]);
        return(-1);
    }

    /* 子プロセスの生成 */
    if((pid=fork())<0){
        perror("popen2");
        close(pipe_c2p[R]);
        close(pipe_c2p[W]);
        close(pipe_p2c[R]);
        close(pipe_p2c[W]);
        return(-1);
    }

    if(pid==0){      /* 子プロセス側 */
        close(pipe_p2c[W]);
        close(pipe_c2p[R]);
        dup2(pipe_p2c[R],0);
        dup2(pipe_c2p[W],1);
        close(pipe_p2c[R]);
        close(pipe_c2p[W]);
        if(execlp("sh","sh","-c",command,NULL)<0){
            perror("popen2");
            close(pipe_p2c[R]);
            close(pipe_c2p[W]);
            exit(1);
        }
    }

    close(pipe_p2c[R]);
    close(pipe_c2p[W]);
    *fd_w=pipe_p2c[W];
    *fd_r=pipe_c2p[R];

    return(pid);
}
