命名管道和無名管道基本相同,但也有不同點:
無名管道隻能由父子程序使用;
但是通過命名管道,不相關的程序也能交換資料。
命名管道的使用
建立管道mkfifo
打開管道open
讀管道read
寫管道write
關閉管道close
删除管道unlink
函數mkfifo
函數作用:建立有名管道
函數原型:
int mkfifo(const char * pathname, mode_t mode);
函數參數:pathname:有名管道的路徑,檔案名 mode:屬性(建立時,該檔案必須不存在)
傳回值 :成功傳回0,出錯:-1
頭檔案 :
#include<sys/types.h>
函數unlink
函數作用:删除檔案
函數原型:
int unlink(const char * pathname);
函數參數:pathname : 檔案路徑+檔案名
傳回值 :成功 : 0;出錯:-1
頭檔案 :
Fifo_wr.c
#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[];
int nwrite;
/*打開管道*/
fd = open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,);
if(argc == )
{
printf("Please send something\n");
exit(-);
}
strcpy(w_buf,argv[]);
/* 向管道寫入資料 */
nwrite = write(fd,w_buf,);
if( nwrite== -)
{
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write %s to the FIFO\n",w_buf);
}
Fifo_rd.c
#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[];
int fd;
int nread;
/* 建立管道 */ //讀寫操作中隻需要有一個檔案中建立有名管道
if((mkfifo(FIFO,O_CREAT|O_EXCL) < ) && (errno != EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,,sizeof(buf_r));
/* 打開管道 */
fd = open(FIFO,O_RDONLY|O_NONBLOCK,);
if(fd == -)
{
perror("open");
exit();
}
while()
{
memset(buf_r,,sizeof(buf_r));
nread = read(fd,buf_r,);
if(nread == -)
{
if(errno == EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep();
}
pause(); /*暫停,等待信号*/
unlink(FIFO); //删除檔案
}
FIFO檔案在使用上和普通檔案有相似之處,但是也有不有
不同之處:
1. 讀取fifo檔案的程序隻能以”RDONLY”方式打開fifo檔案。
2. 寫fifo檔案的程序隻能以”WRONLY”方式打開fifo
3. fifo檔案裡面的内容被讀取後,就消失了。但是普通檔案裡面的内容讀取後還存在。