Linux系统编程:fifo有名管道的使用
生活随笔
收集整理的這篇文章主要介紹了
Linux系统编程:fifo有名管道的使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
fifo介紹
我們可以利用管道進(jìn)行進(jìn)程間通信,已經(jīng)有匿名管道 為啥還要fifo 有名管道呢?有名管道是對(duì)匿名管道的一個(gè)補(bǔ)充,匿名管道是用在有血緣關(guān)系的進(jìn)程間通信。fifo有名管道呢,可以用在任何進(jìn)程間通信。
函數(shù)原型?int mkfifo(const char *pathname, mode_t mode);第一個(gè)參數(shù)是匿名管道的路徑,第二個(gè)參數(shù)創(chuàng)建有名管道的權(quán)限。當(dāng)然man 手冊(cè)是最好的文檔,一定要自己試著去看man 手冊(cè)。
fifo的使用
我們利用2個(gè)不相干的進(jìn)行 通過fifo 有名管道進(jìn)行通信。下面用fifo_read進(jìn)程讀數(shù)據(jù),fifo_write進(jìn)程寫數(shù)據(jù)。
fifo_read.c
#include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h>int main(int argc,char *argv[]) {if(argc < 2){printf("./fifo_read fifoName");exit(1);}int res = access(argv[1],F_OK);if(res==-1)//不可訪問 或者 文件不存在{int re = mkfifo(argv[1],0664);if(re==0){printf("創(chuàng)建fifo文件成功,文件名:%s\n",argv[1]);}else{perror("mkfifo error");exit(1);}}int fd = open(argv[1],O_RDONLY);//從fifo中讀數(shù)據(jù)char temp[1024]={0};while(1){read(fd,temp,sizeof(temp));printf("從fifo中讀取數(shù)據(jù):%s\n",temp);}close(fd);return 0; }fifo_write.c
#include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h>int main(int argc,char *argv[]) {if(argc < 2){printf("./fifo_write fifoName");exit(1);}int res = access(argv[1],F_OK);if(res==-1)//不可訪問 或者 文件不存在{int re = mkfifo(argv[1],0664);if(re==0){printf("創(chuàng)建fifo文件成功,文件名:%s\n",argv[1]);}else{perror("mkfifo error");exit(1);}}int fd = open(argv[1],O_WRONLY);//往fifo中寫數(shù)據(jù)char str[100] = "hello laymond";while(1){sleep(1);write(fd,str,sizeof(str));printf("寫入一條數(shù)據(jù):%s\n",str);}close(fd);return 0; }代碼運(yùn)行檢測
總結(jié)
以上是生活随笔為你收集整理的Linux系统编程:fifo有名管道的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 排序算法:冒泡排序算法优化实现及分析
- 下一篇: linux下c/c++实例之socket