有關無名管道的建立:
#include <sys/stat.h>
int mkfifo(const char* pathname,mode_ mode);
如果是在linux環境下還可以直接在shell終端用mkfifo指令來建立管道檔案。
FIFO常見用途:
(1)FIFO由shell指令使用以便将資料從一條管道線傳送到另一條,為此無需建立中間臨時檔案。
(2)FIFO用于客戶程序-伺服器程序應用程式中,以在客戶程序和伺服器程序之間傳遞資料。
在這裡主要讨論第二種用途。(因為第一種用途我也未曾使用過)
先展現用mkfifo建立一個 fifo管道檔案,将之作為中轉,那麼就可以實作兩個不相幹程序之間的通信了。
寫資料的程式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char* argv[])
{
int fdw = open("./fifo",O_WRONLY);//以寫的形式打開fifo的一端
char buff[128] = {0};
while(1)
{
printf("請輸入\n");
fgets(buff,128,stdin);
if(strncmp(buff,"end",3)==0)
{
break;
}
write(fdw,buff,strlen(buff));//資料被直接寫入fifo
}
close(fdw);
return 0;
}
讀資料的程式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
int main(int argc,char* argv[])
{
int fdr = open("./fifo",O_RDONLY);//以讀的形式打開fifo
while(1)
{
char buff[128]= {0};
int n = read(fdr,buff,127);//把fifo裡面的資料讀到buff上
if(n==0)
{
break;
}
printf("get buff = %s",buff);
}
fflush(stdout);//ensure print succeed
close(fdr);
return 0;
}