2017-11-27 1 views
-1

기본적으로 2 개의 프로세스가있는 프로그램을 만들려고합니다. 첫 번째는 사용자로부터 문자열을 가져 와서 다른 문자열로 전달합니다. 두 번째는 파이프에서 문자열을 읽습니다. 자본화 한 다음 첫 번째 프로세스로 다시 보냅니다. 1 회째는 2 회 스티칭을 인쇄합니다.C 파이프에 작성

내 코드는 String을 전달하고 다른 프로세스는 그것을 읽고 대문자로 사용하지만 두 번째 쓰기 또는 두 번째 읽기에서 오류가 있다고 생각합니다. 여기에 코드입니다 : 여기

#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 
#include <signal.h> 
#define SIZE 15 
int main() 
{ 
int fd[2]; 
pipe(fd); 
if(fork() == 0) 
{ 
char message[SIZE]; 
int length; 

close(fd[1]); 
length = read(fd[0], message, SIZE); 
for(int i=0;i<length;i++){ 
    message[i]=toupper(message[i]); 
    } 
printf("%s\n",message); 
close(fd[0]); 

open(fd[1]); 
write(fd[1], message, strlen(message) + 1); 
close(fd[1]); 
} 
else 
{ 

char phrase[SIZE]; 
char message[SIZE]; 
printf("please type a sentence : "); 
scanf("%s", phrase); 
close(fd[0]); 
write(fd[1], phrase, strlen(phrase) + 1); 
close(fd[1]); 

sleep(2); 

open(fd[0]); 
read(fd[0], message, SIZE); 
close(fd[0]); 
printf("the original message: %s\nthe capitalized version: 
     %s\n",phrase,message); 
} 
return 0; 
} 
+0

"open (fd [1])"... ??? 너 뭐하려고? – TonyB

+1

응답을 다시 보내기위한 두 번째 파이프가 필요할 수도 있습니다. '열린'은 당신이 기대하는 것처럼 보이지 않습니다. – lockcmpxchg8b

답변

1

는 2 파이프 솔루션의 데모는 첫 번째 단어를 캡처 "는 scanf()를"당신이 imployed 유지 ... 것 ... 모든 입력 :

#include <stdio.h> 
#include <unistd.h> 
#include <ctype.h> 
#include <string.h> 
#include <signal.h> 

#define SIZE 15 

int main() 
{ 
    int to_child_fd[2]; 
    int to_parent_fd[2]; 
    pipe(to_child_fd); 
    pipe(to_parent_fd); 

    if (fork() == 0) { 
    char message[SIZE]; 
    int length; 

    close(to_child_fd[1]); /* child closes write side of child pipe */ 
    close(to_parent_fd[0]); /* child closes read side of parent pipe */ 
    length = read(to_child_fd[0], message, SIZE); 
    for (int i = 0; i < length; i++) { 
     message[i] = toupper(message[i]); 
    } 
    printf("child: %s\n", message); 
    write(to_parent_fd[1], message, strlen(message) + 1); 
    close(to_parent_fd[1]); 
    } else { 

    char phrase[SIZE]; 
    char message[SIZE]; 
    printf("please type a sentence : "); 
    scanf("%s", phrase); 
    close(to_parent_fd[1]); /* parent closes write side of parent pipe */ 
    close(to_child_fd[0]); /* parent closes read side of child pipe */ 
    write(to_child_fd[1], phrase, strlen(phrase) + 1); 
    close(to_child_fd[1]); 

    read(to_parent_fd[0], message, SIZE); 
    printf("the original message: %s\nthe capitalized version: %s\n", phrase, message); 
    } 
    return 0; 
} 
+0

정말 고마워요. <3 – user312642

관련 문제