匿名管道pipe前面已经说过了,接下来就说命名管道FIFO;
ide
咱们能够使用如下函数之一来建立一个命名管道,他们的原型以下:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *filename, mode_t mode);
int mknod(const char *filename, mode_t mode | S_IFIFO, (dev_t)0);这两个函数都能建立个FIFO, 注意是建立一个真实存在于文件系统中的文件,filename指定了文件名,mode则指定了文件的读写权限。 mknod是比较老的函数,而使用mkfifo函数更加简单和规范,因此建议在可能的状况下,尽可能使尽可能使用mkfifo而不是mknod。
函数
mkfifo函数的做用是在文件系统中建立一个文件,该文件用于提供FIFO功能,即命名管道。前边讲的那些管道都没有名字,所以它们被称为匿名管道,或简称管道。对文件系统来讲,匿名管道是不可见的,它的做用仅限于在父进程和子进程两个进程间进行通讯。而命名管道是一个可见的文件,所以,它能够用于任何两个进程之间的通讯,无论这两个进程是不是父子进程,也无论这两个进程之间有没有关系。
spa
server.c readorm
#include<stdio.h>server
#include<sys/types.h>进程
#include<sys/stat.h>ip
#include<unistd.h>原型
#include<string.h>string
#include<fcntl.h>it
int main()
{
if(mkfifo("./fifo",S_IFIFO|0666) < 0)
{
perror("mkfifo");
return 1;
}
int fd=open("./fifo",O_RDONLY);
if(fd<0)
{
perror("open");
return 2;
}
char buf[1024];
while(1)
{
memset(buf,'\0',sizeof(buf));
read(fd,buf,sizeof(buf)-1);
printf("client#%s",buf);
}
close(fd);
return 0;
}
client.c write
代码以下:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main()
{
int fd=open("./fifo",O_WRONLY);
if(fd<0)
{
perror("open");
return 2;
}
char buf[1024];
while(1)
{
printf("please enter#");
fflush(stdout);
ssize_t sz=read(0,buf,sizeof(buf)-1);
if(sz>0)
{
buf[sz]='\0';
}
write(fd,buf,strlen(buf));
}
close(fd);
return 0;
}