2017-10-19 16 views
0

基本的には、クライアントプログラムがファイル(コマンドライン入力で指定されたファイル名/パス)からデータを読み取り、そのデータをFIFOにコピーして、 FIFOから読み取り、すべての行を印刷するプログラム。例えばCでファイルの名前を読み取った名前付きパイプ(FIFO)

私はこのように、端末にプログラムを実行する/ etc/passwdファイル、テキストファイルの内容を印刷したい場合:代わりに任意の出力を印刷する、それが出て印刷し、しかし

./server & 
./client < /etc/passwd 

を何も「完了」していない。 なぜですか?
server.c

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

#define FIFONAME "myfifo" 

int main(void){ 

    int n,fd; 
    char buffer[1024]; 
    unlink(FIFONAME); 

    //create FIFO 

    if(mkfifo(FIFONAME,0666)<0){ 
     perror("server: mkfifo"); 
     exit(1); 
    } 
    //open FIFO for reading 
    if((fd = open(FIFONAME, O_RDONLY))<0){ 
     perror("server: open"); 
     exit(1); 
    } 
    //READ from fifo UNTIL end of tile and print 
    //what we get on the standard input 
    while((n=read(fd,buffer,sizeof(buffer)))>0){ 
     write(1, buffer, n); 
    } 

    close(fd); 
    exit(0); 
} 


はここに私のコードです。
client.cを

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

#define FIFONAME "myfifo" 

int main(void){ 

    int n,fd; 
    char buffer[1024]; 

    /* open, read, and display the message from the FIFO */ 
    if((fd = open(FIFONAME, O_WRONLY))<0){ 
     perror("client: open"); 
     exit(1); 
    } 
    //read from standard input and copy data to the FIFO 
    while (fgets(buffer, sizeof(buffer), stdin) != 0){ 
     fgets(buffer, sizeof(buffer), stdin); 
     write(fd, buffer, n); 
    } 


    close(fd); 
    exit(0); 
} 
+0

クライアントが起動する前にサーバーがFIFOを作成する時間があることを確認してください(クライアント側で通常のファイルを作成します) –

+0

@ Jean-FrançoisFabreクライアントの開始前にFIFOを作成するのに十分な時間があります! – fredjohnson

+0

サーバとクライアントの間に 'sleep'を追加できますか?それほど費用はかかりませんが、試してみる価値があります。 –

答えて

2

このコードが間違っている:

while (fgets(buffer, sizeof(buffer), stdin) != 0){ 
     fgets(buffer, sizeof(buffer), stdin); 
     write(fd, buffer, n); 

このループは入力を消費し、再びそれを読み込みます。あなたは最初の(そしておそらく唯一の)bufferを失っています。私は(そうでないかもしれない最高のコードが、作品)だろう:私のコメントで述べたようにFIFOを作成するために、バックグラウンドでサーバを実行して、

while (1){ 
     if (fgets(buffer, sizeof(buffer), stdin)==0) break; 
     write(fd, buffer, n); 
} 

とFIFOを作成するのを待たずにクライアントを実行しています潜在的な競合状態。

+0

あなたの答えをありがとう!あなたが示唆したように私は最初にクライアントプログラムで2秒のスリープを追加しましたが、それでもテキストファイルの出力は「完了」と出力されません。 ' int n、fd; charバッファ[1024]。 /* FIFOからメッセージを開いて読み込み、表示する*/ sleep(2); '//クライアントファイル – fredjohnson

+0

に眠りを追加しましたが、私の答えは完全に読みましたか?あなたのクライアントコードは_wrong_ –

+0

です。それは間違っていますので、クライアントコードをテキストエディタで提案したコードに変更しました。 – fredjohnson

関連する問題