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;

}



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