2013-10-07 2 views
0

child process sp.c의 mp.c에서 만든 pipe을 사용하는 방법을 이해하지 못합니다. 외부 프로세스로 execl을 사용할 때 나는 (0120)에 액세스 할 수 없습니다. execl에 의해 호출 된 자식 프로세스의 파이프에 쓰기

/***************mp.c*****************/ 

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

int main(int argc, char *argv[]) { 
char *procpath = "/mypath/sp"; 
char *procname = "sp"; 
pid_t pid; 
int fd[2]; 
int ret; 
char buf[20]; 
memset(&buf[0], 0, sizeof(buf)); 
ret = pipe(fd); 
if(ret == -1){ 
perror("pipe"); 
exit(1); 
} 
pid = fork(); 
printf("%d\n",pid); 
    if (pid == 0){ 
//dup2(mypipefd[1],STDOUT_FILENO); 
    ret = execl(procpath, procpath, "1","2",NULL); 
    perror("execl failed to run slave program"); 
    exit(1); 
    } 
    else if (pid > 0){ 
    /* Parent process*/ 
    printf("execl ret val = %d",ret); 
    printf("Parent process \n"); 
    close(fd[1]); 
    read(fd[0],buf,15); 
// close(fd[1]); 
    close(fd[0]); 
    printf("buf: %s TEST\n", buf); 
    printf("buf: %s TEST\n", buf); 
    } 
    else{ 
    printf("call to fork failed, no child\n"); 
    exit(-1); 
    } 
exit(0); 
} 

와 생성 과정

...

/***************sp.c*****************/ 

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 
#include <errno.h> 

int main(int argc, char *argv[]){ 
int ret; 
//printf("Child process \n"); 
int fd[2]; 
pipe(fd); 
//dup2(fd[1],1); 
//int out; 
/*ret = dup2(fd[1],1); 
    if (ret = -1){ 
    printf("%s\n", strerror(errno)); 
    };*/ 
//sprintf() 
//printf("%d\n", ret); 
//mypipefd = argv[1]; 
printf("Child process \n"); 
//close(fd[0]); 
write(fd[1], "Hello there!",12); 
close(fd[1]); 
exit(0); 
} 

답변

0

문제는 당신이 각 응용 프로그램에서 다른 파이프를 만드는 것입니다. 파이프를 통해 올바르게 통신하려면 두 프로그램이 동일한 파이프 (파이프 함수로 작성한 파일 설명자 중 하나)를 공유해야합니다.

기본적으로이 문제를 해결하려면 한 응용 프로그램에서 파이프를 만들고 시스템 호출 파이프를 다시 호출하지 않고 파일 설명자를 다른 프로그램에 보내야합니다. 파일 디스크립터는 소켓 유닉스 도메인을 사용하여 다른 프로세스로 보낼 수 있습니다. 이 게시물을 봐 Can I share a file descriptor to another process on linux or are they local to the process?.

관련 문제