2014-11-06 3 views
0

유닉스/리눅스 셸의 파이프 함수를 구현하는 간단한 코드를 작성했습니다.pipe() 함수가있는 간단한 셸

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

void 
cisshPipe(char* command1[], char* command2[]) 

{ 
    int fd[2];//create array for two file descritors 
    pid_t childPid;//To set for child process 
    pipe(fd);//To create pipeline here 

    if((childPid=fork())==-1) 
    { 
     perror("fork here"); 
     exit(1); 
    } 

//The below is the real meat for this subroutine 
    if(childPid==0)//If child process 
    { 
    close(fd[0]);//To close the input of child 
    dup(fd[0]);//To duplicate the input, for the later process 
    } 
    else//For the real output 
    { 
    close(fd[1]);//To close the parent output first 
    execvp(command2[],command2); 
    } 

    } 

그러나 여기서 "execvp (command2 [], command2)"에 대한 컴파일 오류가 있습니다. 부모 출력에 자식 출력을 전달하는 데 사용하는 dup() 함수 때문인 것 같습니다. 그것을 고칠 모든 제안을하시기 바랍니다?

일부 업데이트 :

John의 답변에 감사드립니다. 나는 컴파일 문제를 해결했다. 하지만 그것은 "ls | sort"를 입력 할 때 파이프 함수를 수행 중이다. 나는 여전히 dup() 문제가 여기에 있다고 생각한다.

+0

정확한 메시지를 게시하시기 바랍니다. 오류는 무엇이 잘못되었는지 알려줍니다 ... – clcto

+0

답장을 보내 주셔서 감사합니다. 지금 고쳐. –

+0

전화를 건 기능에 대한 문서를 읽었습니까? [execvp (3)] (http://man7.org/linux/man-pages/man3/execvp.3.html)? 문서화 된대로 호출해야합니다 ... –

답변

1

이 코드는 작동하지만 가능한 모든 오류 검사를 수행하지는 않습니다. 파일을 표준 출력 (또는 표준 출력)으로 리디렉션 한 후 파일 설명자를 닫아야하는 방식과 비슷하게 파이프를 사용하는 경우 dup() 또는 dup2() 표준 입력 또는 출력에 대한 파이프의 한쪽 끝이 필요합니다. 명령을 실행하기 전에 나중에 파이프의 양쪽 끝을 닫으십시오. 파이프가 자식 프로세스에서 유지되는 부모 프로세스에서 만들어지면 파이프의 양쪽 끝이 부모에서도 닫혀 있는지 확인해야합니다.

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

static inline void error(const char *msg) 
{ 
    perror(msg); 
    exit(EXIT_FAILURE); 
} 

static void 
cisshPipe(char **command1, char **command2) 
{ 
    int fd[2]; 
    pid_t childPid; 
    if (pipe(fd) != 0) 
     error("failed to create pipe"); 

    if ((childPid = fork()) == -1) 
     error("failed to fork"); 

    if (childPid == 0) 
    { 
     dup2(fd[1], 1); 
     close(fd[0]); 
     close(fd[1]); 
     execvp(command1[0], command1); 
     error("failed to exec command 1"); 
    } 
    else 
    { 
     dup2(fd[0], 0); 
     close(fd[0]); 
     close(fd[1]); 
     execvp(command2[0], command2); 
     error("failed to exec command 2"); 
    } 
} 

int main(void) 
{ 
    char *ls[] = { "ls", 0 }; 
    char *sort[] = { "sort", "-r", 0 }; 
    cisshPipe(ls, sort); 
    return 0; 
} 

샘플 출력 :

xx.dSYM 
xx.c 
xx 
xma.dSYM 
xma.c 
xma 
ws-c11.c 
… 
am-pm.pl 
2dv.dSYM 
2dv.c 
2dv 
2da.dSYM 
2da.c 
2da 
+0

답변에 많은 감사드립니다. –

3
execvp(command2[],command2); 

[]은 구문 오류입니다. 아마도 :

execvp(command2[0], command2);