Linux下有名管道m(xù)kfifo使用詳解
Linux下實現(xiàn)進程通信的方式有很多種,今天要說的是有名管道,有名管道比命名管道的優(yōu)勢是可以在任何進程之間傳遞數(shù)據(jù)。有名管道通信是依賴于管道文件這種特殊類型文件來進行的。
1.mkfifo命令
mkfifo命令可以創(chuàng)建管道文件,例如:
如上文件類型是p代表的就是管道文件。
2.mkfifo庫函數(shù)
man 3 mkfifo
mkfifo函數(shù)是glibc庫中實現(xiàn)的一個接口,如下利用mkfifo來實現(xiàn)進程之間數(shù)據(jù)傳輸。
server.c
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <assert.h> #include <fcntl.h> #define FIFO_PATH "./fifo" int main() { umask(0); // 創(chuàng)建管道 int ret = mkfifo(FIFO_PATH, 0666); // 打開管道 int fd = open(FIFO_PATH, O_RDONLY); if(fd > 0) { char buf[1024] = {0}; while(1){ //管道讀取數(shù)據(jù) int ret = read(fd, buf, sizeof(buf) - 1); buf[ret] = 0; if(ret > 0){ printf("%s", buf); fflush(stdout); } // 客戶端不寫入數(shù)據(jù),則停止讀取 else if(ret == 0){ printf("client quit\n"); break; } else{ perror("read filed\n"); break; } } } close(fd); return 0; }
client.c
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <assert.h> #include <stdlib.h> #define FIFO_PATH "./fifo" #define WRITE_TIMES 5 /* 標準輸入輸出錯誤輸出 FILE*: stdin stdout stderr 標準輸入輸出錯誤輸出fd: STDIN_FILENO 0 STDOUT_FILENO 1 STDERR_FILENO 2 */ int main() { //打開管道 int fd = open(FIFO_PATH, O_WRONLY); char buf[64] = {0}; int times = 0; while(1) { // 寫入5次 if (++times > WRITE_TIMES) { break; } printf("please input info :"); fflush(stdout); //從標準輸入獲取數(shù)據(jù)寫入進管道。 ssize_t ret = read(0, buf, sizeof(buf) - 1); if(ret > 0){ //將讀取到的數(shù)據(jù)往文件中寫入 buf[ret] = 0; write(fd, buf, sizeof(buf) - 1); } else { perror("read"); } } close(fd); return 0; }
Makefile
.PHONY: all all: server client server: server.c gcc -o $@ $^ client: client.c gcc -o $@ $^ .PHONY: clean clean: rm server client fifo -rf
代碼結(jié)構(gòu):
運行兩個server進程,兩個client進程
從運行結(jié)果看, 兩個client進程往管道寫入5段數(shù)據(jù)信息,兩個server進程從管道讀取數(shù)據(jù),管道有互斥功能,同一時刻只能有一個進程從管道讀取數(shù)據(jù)。
到此這篇關(guān)于Linux下有名管道m(xù)kfifo使用的文章就介紹到這了,更多相關(guān)Linux mkfifo使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一個簡潔的全自動安裝LNMP服務(wù)器環(huán)境的Shell腳本分享
這篇文章主要介紹了一個簡潔的全自動安裝LNMP服務(wù)器環(huán)境的Shell腳本分享,本文腳本在生產(chǎn)環(huán)境上使用了一年多,腳本代碼簡單唯美,需要的朋友可以參考下2014-12-12shell腳本實現(xiàn)linux系統(tǒng)文件完整性檢測
這篇文章主要介紹了shell腳本實現(xiàn)linux系統(tǒng)文件完整性檢測,本文給出的腳本使用對比MD5的方法,檢測linux系統(tǒng)文件是否被替換等問題,需要的朋友可以參考下2014-12-12一個強大的網(wǎng)絡(luò)分析shell腳本分享(實時流量、連接統(tǒng)計)
這篇文章主要介紹了一個強大的網(wǎng)絡(luò)分析shell腳本分享,此腳本包含實時流量統(tǒng)計、連接統(tǒng)計強大功能,需要的朋友可以參考下2014-12-12