2016-07-04 47 views
2

我爲FIFO寫測試。服務器通過FIFO向客戶端寫入字符串「hello」。但似乎這兩個進程都被阻塞了。我認爲先進先出是爲服務器和客戶端的寫入和讀取而打開的。但是這兩個進程什麼都不輸出。當打開FIFO時,爲什麼進程被阻塞

/* FIFO test */ 

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

#define FIFOPATH "/home/hel/fifo" // define file path 

int client(void); 
int server(void); 

int main(void) 
{ 
    pid_t pid; 

    /* create FIFO */ 
    if (mkfifo(FIFOPATH, S_IRUSR | S_IWUSR) < 0) { 
     if (errno == EEXIST) { // already exists, ok 
     } 

     /* error */ 
     else { 
      exit(-1); 
     } 
    } 
    /* create process */ 
    pid = fork(); 
    if (pid < 0) { // error, process exits. 
     exit(-1); 
    } else if (pid == 0) { // child, server 
      server(); 

      return 0; // exit 
    } 

    /* parent, client */ 
    client(); 

    return 0; 
}  

/* server */ 
int server(void) 
{ 
    int ret; 
    int fd; 

    /* open fifo for writing */ 
    if ((fd = open(FIFOPATH, 0200)) < 0) { 
     printf("%s\n", strerror(errno)); 
     return -1; // error 
    } 

    ret = write(fd, "hello", 5); 
    close(fd); 

    return 0; 
} 

/* client */ 
int client(void) 
{ 
    char recvBuf[100]; 
    int fd; 
    int ret; 

    /* open fifo for reading */ 
    if ((fd = open(FIFOPATH, 0400)) < 0) { 
     printf("%s\n", strerror(errno)); 
     return -1; // error 
    } 

    ret = read(fd, recvBuf, 5); 
    printf("ret: %d %d\n", ret, fd); 
    printf("client receive %s\n", recvBuf); 

    close(fd); 
    return 0; 
} 

回答

2

您的代碼有兩個問題。第一個是主要問題。

  1. 傳遞給openflags參數不正確。它們不應該是unix文件許可標誌,因爲它看起來像你提供的。服務器應使用O_WRONLY,客戶端應使用O_RDONLY
  2. write(fd, "hello", 5);read(fd, recvBuf, 5);不會寫入和讀取字符串的終止NUL字符。但是,它被打印爲一個字符串:printf("client receive %s\n", recvBuf);。這會調用未定義的行爲(儘管程序看起來很可能「有效」)。將5更改爲6
0

開()使用下列標誌: -

 O_RDONLY  open for reading only 
     O_WRONLY  open for writing only 
     O_RDWR   open for reading and writing 
     O_NONBLOCK  do not block on open or for data to become available 
     O_APPEND  append on each write 
     O_CREAT   create file if it does not exist 
     O_TRUNC   truncate size to 0 
     O_EXCL   error if O_CREAT and the file exists 
     O_SHLOCK  atomically obtain a shared lock 
     O_EXLOCK  atomically obtain an exclusive lock 
     O_NOFOLLOW  do not follow symlinks 
     O_SYMLINK  allow open of symlinks 
     O_EVTONLY  descriptor requested for event notifications only 
     O_CLOEXEC  mark as close-on-exec 

爲FIFO必須O_RDONLY在客戶端和O_WRONLY在程序中使用的服務器。

0200和0400權限不適用於open()。您可以爲

的#define O_RDONLY 0×0000/打開檢查標誌值以只讀*/

的#define O_WRONLY×0001/打開只寫*/

這就是爲什麼開放在你的情況下,因爲它沒有得到正確的標誌塊。

相關問題