2013-01-05 180 views
3

我一直試圖在我的實驗室週一前得到一些關於FIFO和這個低級I/O的見解,而我遇到了這種情況,我不太明白。FIFO文件和讀取/寫入

方案應:

服務器:

  • 創建的FIFO,
  • 發送5個消息: 「消息#i」,用5秒的間隔,
  • 刪除的FIFO,

客戶端:

  • 從FIFO讀取並顯示消息,
  • 結束,如果有6秒無味精,

而且然而它確實溝通,客戶端顯示不正是我沒有送他,更重要的是,每次新消息到達時,似乎都是從頭開始閱讀。我一直試圖弄清楚,相當長一段時間,它似乎不符合文檔所說的...請幫助! :(

服務器

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

int main(int argc, char* argv[]) 
{  
    int s2c, c2s, i; 
    char fifo_name1[] = "/tmp/fifo1"; 
    char fifo_name2[] = "/tmp/fifo2"; 
    char msg[80], buf[10]; 
    struct stat st; 

    // if no fifos, create 'em 
    if (stat(fifo_name1, &st) != 0) 
     mkfifo(fifo_name1, 0666); 
    if (stat(fifo_name2, &st) != 0) 
     mkfifo(fifo_name2, 0666); 

    s2c= open(fifo_name1, O_WRONLY); 
    c2s= open(fifo_name2, O_RDONLY); 

    // start sending messages, with 5s interval 
    for (i=0; i<5; i++) 
    { 
     printf("Message #%d \n", i); 

     strcat(msg, "Message #"); 
     strcat(msg, itoa(i, buf, 10)); 
     strcat(msg, "\0"); 

     write(s2c, msg, strlen(msg)+1); 

     sleep(5); 
    } 

    // delete fifos 
    unlink(fifo_name1); 
    unlink(fifo_name2); 
    printf("server exit successfully"); 
    return EXIT_SUCCESS; 
} 

客戶

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

int main(int argc, char* argv[]) 
{ 
    int c2s, s2c, c=0; 
    char buf[10]; 

    char fifo_name1[] = "/tmp/fifo1"; 
    char fifo_name2[] = "/tmp/fifo2"; 
    s2c= open(fifo_name1, O_RDONLY); 
    c2s= open(fifo_name2, O_WRONLY); 

    // receive messages 
    while (1) 
    { 
     if (read(s2c, &buf, sizeof(char)*10) > 0) 
     { 
      printf("%s \n", buf); 
      c=0; 
     } 
     sleep(1); 
     c++;  
     if (c>6) 
      break; 
    } 

    printf("client exit successfully"); 
    return EXIT_SUCCESS; 
}  

回答

3

strcat(msg, "Message #");總是附加到字符串已經在msg末,並在循環過程中的字符串是永遠不會重置,更換它與strcpy(msg, "Message #");從頭開始每條新消息。

+0

非常感謝,現在工作! :D看起來像我在一個完全錯誤的地方尋找錯誤,在我身上感到羞恥:( – Kreweta