2017-10-27 11 views
0

다음 코드를 실행할 때 "grep : (표준 입력) : 잘못된 파일 설명자"가 표시됩니다. 왜 그런가? 프로그램이 홈 디렉토리를 출력하기로되어 있습니다. 감사!"grep : (표준 입력) : 잘못된 파일 설명자"를 나타내는 홈 디렉토리를 인쇄하는 C 프로그램

else if(close(fd[0] == -1)) 
... 
else if(close(fd[1]==-1)) 

그것은해야한다 :

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

int main(void) { 
pid_t childpid; 
int fd[2]; 

if(pipe(fd) == -1) { /* setup a pipe */ 
    perror("Failed to setup pipeline"); 
    return 1; 
} 
if((childpid = fork()) == -1){ /* fork a child */ 
    perror("Failed to fork a child"); 
    return 1; 
} 
if(childpid == 0){ /* env is the child */ 

    if(dup2(fd[1],STDOUT_FILENO)==-1) 
     perror("Failed to redirect stdout of env"); 
    else if(close(fd[0] == -1)) /* close unused file descriptor */ 
     perror("Failed to close extra pipe descriptors on env"); 
    else { 
     execl("/usr/bin/env", "env", NULL); /* execute env */ 
     perror("Failed to exec env"); 
    } 
    return 1; 
} 
if(dup2(fd[0],STDIN_FILENO)==-1) 
/*grep is the parent*/ 
    perror("Failed to redirect stdin of grep"); 
else if(close(fd[1]==-1)) 
    perror("Failed to close extra pipe file descriptors on grep"); 
else { 
    execl("/bin/grep", "grep", "HOME", NULL); /*execute "grep HOME"*/ 
    perror("Failed to exec grep"); 
} 
return 1; 
} 
+0

첫 번째 테스트에서 if (pipe (fd [0]) == -1) {}? fd의 주소가 적절한 기술자가 아니기 때문에 –

+0

'grep HOME'은 정확히 무엇을합니까? 거기에 파일 이름이 누락 되었습니까? – Serge

답변

0

오류는 논문에서 2 선입니다

그렇지 않으면 점점 홈페이지 ENV는 외부 프로그램 실행하지 않고 실현 될 수
else if(close(fd[0]) == -1) 
... 
else if(close(fd[1]) == -1) 

:

#include <stdio.h> 
#include <string.h> 

int main(int argc, char **argv, char** envp) 
{ 
    char** env; 
    for (env = envp; *env != 0; env++) 
    { 
     char* thisEnv = *env; 
     if (strncmp(thisEnv, "HOME=", 5) == 0) 
     { 
      printf("%s\n", thisEnv + 5); 
      break; 
     } 
    } 
    return(0); 
} 
+0

'#include '와'const char * home = getenv ("HOME");은 어떨까요? –

관련 문제