FIFO 上的 I/O 操作本质上与普通管道的操作相同,只有一个主要例外。 应该使用 ``open'' 系统调用或库函数来物理地打开到管道的通道。 对于半双工管道,这是不必要的,因为管道驻留在内核中,而不是在物理文件系统上。 在我们的例子中,我们将把管道视为一个流,使用 fopen() 打开它,并使用 fclose() 关闭它。
考虑一个简单的服务器进程
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: fifoserver.c
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/stat.h>
#define FIFO_FILE "MYFIFO"
int main(void)
{
FILE *fp;
char readbuf[80];
/* Create the FIFO if it does not exist */
umask(0);
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
{
fp = fopen(FIFO_FILE, "r");
fgets(readbuf, 80, fp);
printf("Received string: %s\n", readbuf);
fclose(fp);
}
return(0);
}
由于 FIFO 默认是阻塞的,请在编译后在后台运行服务器
$ fifoserver&
我们稍后将讨论 FIFO 的阻塞行为。 首先,考虑以下我们服务器的简单客户端前端
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: fifoclient.c
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define FIFO_FILE "MYFIFO"
int main(int argc, char *argv[])
{
FILE *fp;
if ( argc != 2 ) {
printf("USAGE: fifoclient [string]\n");
exit(1);
}
if((fp = fopen(FIFO_FILE, "w")) == NULL) {
perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}