管道通信 1.定義: 1)管道式單向的,先進先出的,把一個程序的輸出和另一個程序的輸入連接配接在一起。 2)一個程序(寫程序)在管道的尾部寫入資料,另一個程序(讀程序)從管道的頭部讀出資料。 3)資料被一個程序讀出後,将被從管道中删除,其它讀程序将不能再讀到這些資料。(管道提供了簡單的流控制機制,程序試圖讀空管道時,程序将阻塞。同樣,管道已經滿時,程序再試圖管道寫入資料,程序将阻塞) 2.管道建立 1)無名管道:用于父程序和子程序的通信 建立:pipe() int pipe(int filedis[2]) 當一個管道建立時,它會建立兩個檔案描述符:filedis[0]用于讀管道,filedis[1]用于寫管道 管道關閉:關閉管道隻需将這兩個檔案描述符關閉即可,可以使用普通的close函數逐個關閉 管道讀寫 管道用于不同程序間的通信。通常先建立一個管道,再通過fork函數建立一個子程序,該子程序會繼承父進 程 所建立的管道。 *必須在系統調用fork()前調用pipe(),否則子程序将不會繼承檔案描述符
2)命名管道 命名管道和無名管道基本相同,不同點在于:無名管道隻能由父子程序使用,但通過命名管道,不相關的程序也能交換資料。 建立: #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname,mode_t mode) pathname:FIFO檔案名 mode:屬性: 一旦建立了一個fifo,就可以用open打開它,一般的檔案通路函數(close,read,write等)都可以用于fifo 操作: 打開FIFO時,非阻塞标志(O_NONBLOCK)将對以後的讀寫産生以下影響: 1)沒有使用O_NONBLOCK:通路要求無法滿足時程序将阻塞。如試圖讀取空的FIFO,将導緻程序阻塞。 2)使用O_NONBLOCK:通路要求無法滿足時不阻塞,立即出錯傳回,errno是ENXIO。
代碼示範: /fifo_read #include <sys/types.h> #include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"
main(int argc,char** argv)
{
char buf_r[100];
int fd;
int nread;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,0,sizeof(buf_r));
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1)
{
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause();
unlink(FIFO); //删除檔案
}
/fifo_write// #include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER "/tmp/myfifo"
main(int argc,char** argv)
{
int fd;
char w_buf[100];
int nwrite;
fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
if(argc==1)
{
printf("Please send something\n");
exit(-1);
}
strcpy(w_buf,argv[1]);
if((nwrite=write(fd,w_buf,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write %s to the FIFO\n",w_buf);
}