linux 进程间通信之管道和FIFO
来源:互联网 发布:积分兑换系统源码 php 编辑:程序博客网 时间:2024/04/29 03:57
一.管道
1.可有多个进程向一个进程写入数据,读入数据的进程只能有一个
2.管道通信只能支持单向通信,如果实现双向通信效果,则需要建立两个管道
3.管道只支持有父子关系和有共同父进程关系的子进程之间的进程通信
int pipe(int filedes[2]);
功能:filedes 为两个元素的整型数组,pipe 调用产生一个管
道,管道的读描述符存入filedes[0],管道的写描述符存入
filedes[1]。一个进程可以向filedes[1]中写入数据,另一个进程
可以从filedes[0]中读出数据。
代码举例如下:
/* * piperw.c - The correct way to open a pipe and fork * a child process. */#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <limits.h>#define BUFSZ PIPE_BUFvoid err_quit(char *msg);int main(int argc, char *argv[]){int fd[2]; /* File descriptor array for the pipe */int fdin; /* Descriptor for input file */char buf[BUFSZ];int pid, len;/* Create the pipe */if((pipe(fd)) < 0)err_quit("pipe"); /* Fork and close the appropriate descriptors */if((pid = fork()) < 0)err_quit("fork");if (pid == 0) {/* Child is reader, close the write descriptor */close(fd[1]);while((len = read(fd[0], buf, BUFSZ)) > 0)write(STDOUT_FILENO, buf, len);close(fd[0]);} else {/* Parent is writer, close the read descriptor */close(fd[0]);if((fdin = open(argv[1], O_RDONLY)) < 0) { perror("open"); /* Send something since we couldn't open the input */ write(fd[1], "123\n", 4); } else { while((len = read(fdin, buf, BUFSZ)) > 0) write(fd[1], buf, len); close(fdin); } /* Close the write descriptor */ close(fd[1]); } waitpid(pid, NULL, 0);exit(EXIT_SUCCESS);} void err_quit(char *msg){perror(msg);exit(EXIT_FAILURE);}
二,FIFO(命名管道)
因为以上提到的管道只支持父子进程或有相同父进程之间的子进程之间的进程通信,故而为了实现非此关系外的进程通信,FIFO油然而生,他通过一个文件写入读取实现管道通信。
/* * rdfifo.c - Create a FIFO and read from it */#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include <limits.h>int main(void){int fd;/* Descriptor for FIFO */int len; /* Bytes read from FIFO */char buf[PIPE_BUF];mode_t mode = 0666;if((mkfifo("fifo1", mode)) < 0) {perror("mkfifo");exit(EXIT_FAILURE);} /* Open the FIFO read-only */ if((fd = open("fifo1", O_RDONLY)) < 0) { perror("open"); exit(EXIT_FAILURE); } /* Read and display the FIFO's output until EOF */ while((len = read(fd, buf, PIPE_BUF - 1)) > 0) printf("rdfifo read: %s", buf); close(fd); exit(EXIT_SUCCESS);}
- Linux进程通信之管道和FIFO
- Linux进程通信之管道和FIFO
- linux 进程间通信之管道和FIFO
- 进程间通信之管道和FIFO
- Linux进程间通信(一)之无名管道(PIPE)和有名管道(FIFO)
- 命名管道(FIFO) Linux进程进程间的通信之命名管道(FIFO)
- linux进程间通信之管道(pipe与fifo)
- Linux进程间通信之命名管道(FIFO)
- 【Linux】进程间通信之管道pipe与FIFO
- Linux环境进程间通信(一)管道和FIFO
- Linux环境进程间通信(一)管道和FIFO
- linux进程间的通信方式:管道和FIFO
- Linux进程间通信-FIFO管道
- 【Linux】进程间通信-命名管道FIFO
- 【Linux】进程间通信-命名管道FIFO
- 【Linux进程间通信】 - 命名管道FIFO
- 【Linux】进程间通信-命名管道FIFO
- Linux进程间通信-FIFO(命名管道)
- MFC 学习笔记(1)
- Oracle远程客户端配置
- I PAID 我付的。
- VS2008中自动对齐快捷键
- 算法书籍
- linux 进程间通信之管道和FIFO
- x264_median 函数分析
- 杨辉三角
- 解决Android离线文档打开慢的问题
- 学习asp.net完整步骤
- android开发给linearlayout设置边框
- Settings(系统设置app)
- 出现“无法在发生错误时创建会话,请检查 PHP 或网站服务器日志,并正确配置 PHP 安装”时的方法
- vi配置中的方向键和退格键问题