본문 바로가기

IT

theFinale.c

// pipe를 실행하는 프로그램이다.


// 두 개의 명령어를 받아

// pipe를 실행하고, fork를 해서 자식프로세스라면, 입력을 닫고, 출력을 stdout으로 설정한 후, pipe를 닫는다.

// 그리고 먼저 들어온 명령어를 실행. 부모 프로세스라면, 출력을 닫고, 입력을 stdin으로 설정한 후 pipe를 닫는다.

// 그리고 두번째로 들어온 명령어를 실행.



#include                <stdio.h>

#include                <unistd.h>


#define         oops(m,x)               { perror(m); exit(x); }


main(int ac, char **av)

{

        int     thepipe[2],

                newfd,

                pid;

        if ( ac !=3) {

                fprintf(stderr, "usage : pipe cmd1 cmd2\n");

                exit(1);

        }

        if ( pipe (thepipe ) == -1)

                oops ("Cannot get a pipe", 1);

        if (    (pid = fork()) == -1)

                oops("Cannot fork", 2);

        if ( pid > 0 ){

                close(thepipe[1]);

                if ( dup2(thepipe[0], 0) == -1)

                        oops("could not redirect stdin" ,3);

                            close(thepipe[0]);

                execlp ( av[2], av[2], NULL);

                oops (av[2], 4);

        }

        close(thepipe[0]);

        if (dup2(thepipe[1], 1) == -1)

                oops("could not redirect stdout", 4);

        close(thepipe[1]);

        execlp ( av[1], av[1], NULL);

        oops(av[1], 5);

}



'IT' 카테고리의 다른 글

popen example  (0) 2014.11.19
tiny bc  (0) 2014.11.19
redirect1.c  (0) 2014.11.12
method2.c  (0) 2014.11.12
method1.c  (0) 2014.11.12