linux中的命名管道FIFO

匿名管道pipe前面已经说过了,接下来就说命名管道FIFO;

我们可以使用以下函数之一来创建一个命名管道,他们的原型如下:
#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功能,即命名管道。前边讲的那些管道都没有名字,因此它们被称为匿名管道,或简称管道。对文件系统来说,匿名管道是不可见的,它的作用仅限于在父进程和子进程两个进程间进行通信。而命名管道是一个可见的文件,因此,它可以用于任何两个进程之间的通信,不管这两个进程是不是父子进程,也不管这两个进程之间有没有关系。

server.c read

#include<stdio.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<unistd.h>

#include<string.h>

#include<fcntl.h>

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;

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章