linux 命名管道实例详解
生活随笔
收集整理的這篇文章主要介紹了
linux 命名管道实例详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
服務器
linux進程間通信——命名管道
FIFO(命名管道)不同于匿名管道之處在于它提供⼀個路徑名與之關聯,以FIFO的⽂件形式存儲于⽂件系統中。命名管道是⼀個設備⽂件,因此,即使進程與創建FIFO的進程不存在親緣關系,只要可以訪問該路徑,就能夠通過FIFO相互通信。值得注意的是,FIFO(first input first output)總是按照先進先出的原則⼯作,第⼀個被寫⼊的數據將⾸先從管道中讀出。
創建命名管道的系統函數有兩個:mknod和mkfifo。兩個函數均定義在頭⽂件sys/stat.h,函數原型如下:
#include <sys/types.h> #include <sys/stat.h> int mknod(const char *path,mode_t mod,dev_t dev); int mkfifo(const char *path,mode_t mode);
函數mknod參數中path為創建的命名管道的全路徑名:mod為創建的命名管道的模式,指明其存取權限;dev為設備值,該值取決于⽂件創建的種類,它只在創建設備⽂件時才會⽤到。這兩個函數調⽤成功都返回0,失敗都返回-1。下⾯使⽤mknod函數創建了⼀個命名管道:
umask(0);
if (mknod(/tmp/fifo,S_IFIFO | 0666) == -1)
{
perror(mkfifo error);
exit(1);
}
函數mkfifo前兩個參數的含義和mknod相同。下⾯是使⽤mkfifo的⽰例代碼:
umask(0);
if (mkfifo(/tmp/fifo,S_IFIFO|0666) == -1)
{
perror(mkfifo error!);
exit(1);
}
下面為一個試例:
read端
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#define PATH ./fifo
#define SIZE 128
int main()
{
umask(0);
if (mkfifo (PATH,0666|S_IFIFO) == -1)
{
perror (mkefifo error);
exit(0);
}
int fd = open (PATH,O_RDONLY);
if (fd<0)
{
printf(open fd is error\\n);
return 0;
}
char Buf[SIZE];
while(1){
ssize_t s = read(fd,Buf,sizeof(Buf));
if (s<0)
{
perror(read error);
exit(1);
}
else if (s == 0)
{
printf(client quit! i shoud quit!\\n);
break;
}
else
{
Buf[s] = \'\\0\';
printf(client# %s ,Buf);
fflush(stdout);
}
}
close (fd);
return 3;
}
下面為weite端:
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
#define PATH ./fifo
#define SIZE 128
int main()
{
int fd = open(PATH,O_WRONLY);
if (fd < 0)
{
perror(open error);
exit(0);
}
char Buf[SIZE];
while(1)
{
printf(please Enter#:);
fflush(stdout);
ssize_t s = read(0,Buf,sizeof(Buf));
if (s<0)
{
perror(read is failed);
exit(1);
}
else if(s==0)
{
printf(read is closed!);
return 1;
}
else{
Buf[s]= \'\\0\';
write(fd,Buf,strlen(Buf));
}
}
return 0;
}
打開兩個終端:
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
總結
以上是生活随笔為你收集整理的linux 命名管道实例详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑意外关机后VMware中linux不
- 下一篇: CentOS 8.1下搭建LEMP(Li