標籤:linux 管道 fifo 讀寫規則 實踐
概述
(匿名)管道應用的一個限制就是只能在具有共同祖先(具有親緣關係)的處理序間通訊。
如果我們想在不相關的進程之間交換資料,可以使用FIFO檔案來做這項工作,它經常被稱為具名管道;具名管道是一種特殊類型的檔案.
管道應用
1)建立一個具名管道
具名管道可以從命令列上建立:
$ mkfifo <filename>
具名管道在程式裡建立:
#include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode);
匿名管道 VS. 具名管道
1)匿名管道由pipe函數建立並開啟。
具名管道由mkfifo函數建立,開啟用open
2)FIFO(具名管道)與pipe(匿名管道)之間唯一的區別在它們建立與開啟的方式不同,一但這些工作完成之後,它們具有相同的語義。
具名管道的開啟規則
1)讀開啟FIFO
O_NONBLOCK disable(阻塞):阻塞直到有相應進程為寫而開啟該FIFO
O_NONBLOCK enable(非阻塞):立刻返回成功
2)寫開啟FIFO
O_NONBLOCK disable:阻塞直到有相應進程為讀而開啟該FIFO
O_NONBLOCK enable:立刻返回失敗,錯誤碼為ENXIO
具名管道的讀寫規則
同匿名管道
FIFO編程實踐
/**說明:利用管道,兩個進程間進行檔案複製。進程writefifo: 讀input.txt檔案寫入管道fifo進程readfifo:讀管道fifo寫入output.txt檔案*/
//1:writefifo//write fifo, read from fileint main(){ //建立FIFO if (mkfifo("./myFifo",0644) == -1) { err_exit("mkfifo error"); } //開啟管道 int fifofd = open("./myFifo",O_WRONLY); if (fifofd == -1) { err_exit("open fifo error"); } //開啟檔案 int filefd = open("./input.txt",O_RDONLY); if (filefd == -1) { err_exit("open file error"); } //const int BUFSIZ = 1024; char buf[BUFSIZ]; int readCount = 0; while ((readCount = read(filefd,buf,BUFSIZ)) > 0) { write(fifofd,buf,readCount); } close(fifofd); close(filefd); cout << "Write FIFO OK..." << endl; return 0;}
//2:readfifo//read fifo, write to fileint main(){ //開啟FIFO int fifofd = open("./myFifo",O_RDONLY); if (fifofd == -1) { err_exit("open fifo error"); } //開啟檔案 int filefd = open("./output.txt",O_WRONLY|O_CREAT,0644); if (filefd == -1) { err_exit("open file error"); } char buf[BUFSIZ]; int readCount = 0; while ((readCount = read(fifofd,buf,BUFSIZ)) > 0) { write(filefd,buf,readCount); } close(fifofd); close(filefd); cout << "Read FIFO OK..." << endl; return 0;}
附-FIFO手冊頁(man 3 mkfifo)
MKFIFO(3) Linux Programmer‘s Manual MKFIFO(3)NAME mkfifo - make a FIFO special file (a named pipe)SYNOPSIS #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode);DESCRIPTION mkfifo() makes a FIFO special file with name pathname. mode specifies the FIFO‘s permissions. It is modified by the process‘s umask in the usual way: the permissions of the created file are (mode & ~umask). A FIFO special file is similar to a pipe, except that it is created in a different way. Instead of being an anonymous communications channel, a FIFO special file is entered into the filesystem by calling mkfifo(). Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa. See fifo(7) for nonblocking handling of FIFO special files.RETURN VALUE On success mkfifo() returns 0. In the case of an error, -1 is returned (in which case, errno is set appropriately).
Linux管道(具名FIFO)