Linux 进程通信之FIFO
生活随笔
收集整理的這篇文章主要介紹了
Linux 进程通信之FIFO
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
FIFO 有名管道,實(shí)現(xiàn)無(wú)血緣關(guān)系進(jìn)程通信。
----創(chuàng)建一個(gè)管道的偽文件
a.mkfifo testfifo 命令創(chuàng)建
b.也可以使用函數(shù)int mkfifo(const char *pathname, mode_t mode);
----內(nèi)核會(huì)針對(duì)fifo文件開(kāi)辟一個(gè)緩沖區(qū),操作fifo文件,可以操作緩沖區(qū),實(shí)現(xiàn)進(jìn)程間通信–實(shí)際上就是文件讀寫(xiě)
man 3 mkfifo
注意事項(xiàng):
FIFOs
Opening the read or write end of a FIFO blocks until the other end is also opened (by another process or thread). See
fifo(7) for further details.
打開(kāi)fifo文件時(shí)候,read端會(huì)阻塞等待write端open,write端同理,也會(huì)阻塞等待另外一段打開(kāi)。
代碼示例:
file_w.c 寫(xiě)端
file_r.c 讀端
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h>int main(int argc, char *argv[]) {if(argc != 2) {printf("./a.out filename1\n");return -1;}printf("begin open r\n");int o_ret = open(argv[1], O_RDONLY);printf("end open r\n");char buf[256];int num = 0;while (1) {memset(buf, '\0', sizeof(buf));read(o_ret, buf, sizeof(buf));printf("strlen(buf) = %d\n", strlen(buf));printf("read is%s\n", buf);}close(o_ret);return 0; }總結(jié)
以上是生活随笔為你收集整理的Linux 进程通信之FIFO的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 不孕不育是件很可怕的事情吗
- 下一篇: 孟来财传奇剧情介绍