linux程序通訊-FIFO
阿新 • • 發佈:2018-12-15
FIFO 即有名管道可以在不相關的程序進行資料交換
FIFO的建立
#include<sys/stat.h>
int mkfifo(const char *path,mode_t mode);
成功返回0,出錯返回-1
mode引數:與open的引數相同,表示許可權,不考慮移植入,可以直接用資料表示。 path:路徑
建立一個FIFO之後,我們要用open函式開啟它。FIFO的容量是有限制的,定義了一個常量PIPE_BUF,在linux下該值是4096。
下面給出兩個歷程,一個寫歷程,一個讀歷程。 在第一個程式碼中,我們建立一個FIFO,並將從檔案讀來的資料,寫入其中
#include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <limits.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> int main() { const char *file_name="my_fifo"; char *file1="datatxt"; //在這個檔案中儲存了資料 int res=0; int pipe_fd=-1; int data_fd=-1; char buffer[PIPE_BUF+1]; //PIPE_BUF是一個常量,在linux中是4096 int bytes_sent = 0; if(access(file_name,F_OK)==-1){ //若管道不存在,就建立它 res=mkfifo(file_name,0777); if(res!=0) fprintf(stderr,"can not create fifo %s",file_name); exit(1); } printf("process %d open fifo for write\n",getpid()); pipe_fd=open(file_name,O_WRONLY); data_fd=open(file1,O_RDONLY); if(pipe_fd!=-1) { int bytes_read=0; bytes_read=read(data_fd,buffer,PIPE_BUF); //將檔案中的資料讀到buffer中 buffer[bytes_read]='/0'; while(bytes_read > 0) { res = write(pipe_fd, buffer, bytes_read); //往fifo中寫資料 if(res == -1) { fprintf(stderr, "Write error on pipe\n"); exit(1); } bytes_sent += res; //如果檔案中資料,大於4096,做個累加,繼續讀 bytes_read = read(data_fd, buffer, PIPE_BUF); buffer[bytes_read] = '\0'; } close(pipe_fd); close(data_fd); }else exit(1); printf("Process %d finished\n", getpid()); exit(0); }
在第二個歷程中,我們將從上面歷程建立的FIFO中讀取資料,並將其寫入至一個檔案。
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <string.h> int main() { const char *fifo_name = "my_fifo"; int pipe_fd = -1; int data_fd = -1; int res = 0; int open_mode = O_RDONLY; char buffer[PIPE_BUF + 1]; int bytes_read = 0; int bytes_write = 0; memset(buffer, '\0', sizeof(buffer)); //清一下快取 pipe_fd = open(fifo_name, open_mode); //開啟我們的有名管道 data_fd = open("DataFormFIFO.txt", O_WRONLY|O_CREAT, 0644); //建立一個檔案,開啟,只寫 if(pipe_fd != -1) { do { res = read(pipe_fd, buffer, PIPE_BUF); //從管道讀取資料到buffer bytes_write = write(data_fd, buffer, res); //再寫到建立的新檔案中 bytes_read += res; }while(res > 0); close(pipe_fd); close(data_fd); } else exit(1); exit(0); }
FIFO的用途 1)shell命令使用FIFO將資料從一條管道傳送到另一條時,無需建立臨時檔案。 2)客戶程序-伺服器程序應用程式中,FIFO用作匯聚點,在客戶程序和伺服器程序之間傳送資料。