해바

Lab #12 본문

System Programming

Lab #12

Bacha 2019. 11. 18. 13:06

pipe(), fork(), execlp(), system call 들을 사용하여 "ps -ef | grep telnet"의 동작을 구현한다.

  • 부모 프로세스는 파이프를 통해서 "ps -ef" 명령 결과를 출력한다.
  • 자식 프로세스는 부모 프로세스가 출력한 결과를 받아 "grep telnet" 명령을 수행한다.

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main() {
    int fd[2];
    pid_t pid;

    if(pipe(fd) != 0) perror("pipe");

    if((pid = fork()) == -1) perror("fork");
    else if(pid == 0) {
        close(fd[1]);
        if(fd[0] != 0) {
            dup2(fd[0], 0);
            close(fd[0]);
        }

        execlp("grep", "grep", "telnet", (char*) 0);
    }
    else {
        close(fd[0]);

        if(fd[1] != 1) {
            dup2(fd[1], 1);
            close(fd[1]);
        }

        execlp("ps", "ps", "-ef", (char*) 0);
    }

    return 0;
}

 

 

컴파일 :

%gcc pipe.c

 

실행 :

%./a.out

'System Programming' 카테고리의 다른 글

Lab #14  (0) 2019.11.18
Lab #13  (0) 2019.11.18
Lab #11  (0) 2019.11.18
Lab #10  (0) 2019.11.18
Lab #9  (0) 2019.11.18
Comments