2016-12-06 23 views
4

私は2つのプログラム(write.cとread.c)を持っています。私は、標準入力から名前付きパイプに連続的に書き込み、反対側でそれを読み込み(標準​​出力に書き込む)たいと思います。私は何か仕事をしましたが、それは正しく機能していません。もう一方のプログラムは、間違った順序で読み込んだり、特殊文字を読み込んだりします。私はまた、指定されたパイプ出力を特定の文字列と比較できるようにしたい。Cの名前付きパイプの書き込みと読み込み方法は?

write.c:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 
#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 

#define BUFFSIZE 512 
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); } 

void main() 
{ 
    int fd, n; 

    char buf[BUFFSIZE]; 


    mkfifo("fifo_x", 0666); 
    if ((fd = open("fifo_x", O_WRONLY)) < 0) 
     err("open") 

    while((n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0) { 
     if (write(fd, buf, strlen(buf)) != strlen(buf)) { 
      err("write"); 
     } 
    } 
    close(fd); 
} 

read.c:入力の

#include <fcntl.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define BUFFSIZE 512 
#define err(mess) { fprintf(stderr,"Error: %s.", mess); exit(1); } 

void main() 
{ 
    int fd, n; 
    char buf[BUFFSIZE]; 

    if ((fd = open("fifo_x", O_RDONLY)) < 0) 
     err("open") 


    while((n = read(fd, buf, BUFFSIZE)) > 0) { 

     if (write(STDOUT_FILENO, buf, n) != n) { 
      exit(1); 
     } 
    } 
    close(fd); 
} 

例:

とにかく、ここでは両方のファイルからのコードです 誤った出力の

hello how are you 
123 
test 

例:入力の

hello how are you 
b123 
o how are you 
btest 
how are you 
b 

別の例:

test 
hi 

および出力:

test 
hi 
t 

答えて

4

バッファ読み込みして、変更が有効なC文字列ではありませんので、

write(fd, buf, strlen(buf)) != strlen(buf) // write.c 

は未定義の動作です。あなたはread()と、n個のオクテットを読むので、あなたは

write(fd, buf, n) != n 

を行う必要があります。

あなたはn必要がありますが、ssize_tなくintman readの種類read.cのためではなく、write.c


のためにそれを行うので、それは面白いです。


main()は、どのような理由..感謝を知っているうわー、私は実際には最初にそれが正しいいたintDeclare main prototype

+1

返しますが、神のためにそれを変更しなければなりません。 – mythic

関連する問題