2017-11-27 4 views
-1

私は基本的に2つのプロセスを持つプログラムを作成しようとしています。最初の文字列はユーザ​​ーから文字列を受け取り、もう一方の文字列に渡します。 2ndはパイプから文字列を読み込みます。それを大文字にしてから最初のプロセスに送り返します。 1回目は2回のスティッキングを印刷します。Cのパイプに書き込む

私のコードは文字列を渡し、他のプロセスはそれを読み込んで大文字化しますが、2回目の書き込みや2回目の読み込みにエラーがあると思います。ここではコードです:ここで

#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

おそらく、応答を返すための第2のパイプが必要です。 「オープン」は、あなたが期待しているようにはしません。 – 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

関連する問題