2013-05-13 87 views
0

我使用FIFO作爲簡單的讀/寫程序,用戶輸入由寫入函數寫入標準輸出。但問題是,我能否在不創建子進程的情況下運行此程序(使用fork()操作)。從我從有關FIFO的例子中看到,大多數讀/寫程序都是用2個文件完成的 - 一個用於讀取,一個用於寫入。我可以在文件中完成這些嗎?沒有子進程的命名管道

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

/* read from user */ 
void reader(char *namedpipe) { 
    char c; 
    int fd; 
    while (1) { 
    /* Read from keyboard */ 
    c = getchar();  
    fd = open(namedpipe, O_WRONLY); 
    write(fd, &c, 1); 
    fflush(stdout); 
    } 
} 

/* writes to screen */ 
void writer(char *namedpipe) { 
    char c; 
    int fd; 
    while (1) { 
    fd = open(namedpipe, O_RDONLY); 
    read(fd, &c, 1); 
    putchar(c); 
    } 
} 

int main(int argc, char *argv[]) { 
    int child,res;    

    if (access("my_fifo", F_OK) == -1) { 
    res = mkfifo("my_fifo", 0777); 
    if (res < 0) { 
    return errno; 
    } 
    } 

    child = fork();  
    if (child == -1)  
     return errno; 
    if (child == 0) {  
     reader("my_fifo"); 
    } 
    else {     
     writer("my_fifo"); 
    } 


    return 0; 
}      

回答

0

您需要對該文件進行鎖定,否則您可能會嘗試在其他人正在寫入時進行閱讀。您還需要刷新寫入緩衝區,否則實際上不會記錄對fifo的更改,直到內核寫入緩衝區填滿並寫入文件(在linux中,寫入並不保證在該時刻發生寫入。我看到你正在刷新標準輸出,但是你還應該在文件描述符上使用fsync,這將導致文件在任何寫入操作期間被鎖定,以至於其他人都無法寫入。爲了鎖定文件以便讀取,你可能有使用信號量。