命名管道(FIFO)和无名管道基本相同,但也有不同点:无名管道只能由父子进程使用;但是通过命名管道,不相关的进程也能交换数据。
#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。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//创建命名管道
int main()
{
int ret = mkfifo("/home/mkfifo", 0777);
if (ret == -1)
{
perror ("mkfifo");
return -1;
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#define SIZE 1024
//从终端输入,并将输入写入管道
int main()
{
int fd = open("/home/mkfifo", O_WRONLY);
if (fd== -1)
{
perror ("mkfifo");
return -1;
}
char buf[SIZE];
while (1)
{
fgets (buf, SIZE, stdin);
write (fd, buf, strlen(buf));
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#define SIZE 1024
//从管道内读数据
int main()
{
int fd = open("/home/mkfifo", O_RDWR);
if (fd == -1)
{
perror ("mkfifo");
return -1;
}
char buf[SIZE];
while (1)
{
int ret = read (fd, buf, SIZE);
buf[ret] = '\0';
printf ("读到 %d 字节: %s\n", ret, buf);
}
return 0;
}