使用 FIFO 实现进程间通信示例
来源:互联网 发布:淘宝站外活动销量 编辑:程序博客网 时间:2024/05/22 12:42
第一个程序是数据生产者程序。它在需要时创建管道,然后尽可能快地向管道中写入数据。为了方便起见,本程序没有初始化缓冲区。
生产者程序
/*数据生产者*/#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <fcntl.h>#include <limits.h>#include <sys/types.h>#include <sys/stat.h>#define FIFO_NAME "/tmp/my_fifo"#define BUFFER_SIZE PIPE_BUF#define TEN_MEG (1024 * 1024 *10 )int main(){ int pipe_fd; int res; int open_mode = O_WRONLY; int bytes_sent = 0; char buffer[BUFFER_SIZE + 1]; if( -1 == access(FIFO_NAME, F_OK) ) { res = mkfifo( FIFO_NAME, 0777 ); //创建一个FIFO if( 0 != res ) { fprintf( stderr, "Could not create fifo %s\n", FIFO_NAME ); exit( EXIT_FAILURE ); } } printf("Process %d opening FIFO O_WRONLY\n", getpid() ); pipe_fd = open( FIFO_NAME, open_mode ); printf("Process %d result %d\n", getpid(), pipe_fd); if( -1 != pipe_fd ) { while( bytes_sent < TEN_MEG ) { res = write( pipe_fd, buffer, BUFFER_SIZE ); if( -1 == res ) { fprintf( stderr, "Write error on pipe\n"); exit( EXIT_FAILURE ); } bytes_sent += res; } close( pipe_fd ); } else exit( EXIT_FAILURE ); printf("Process %d finished\n", getpid() ); exit( EXIT_SUCCESS );}
消费者程序
第二个程序是消费者程序,它从 FIFO 读取数据并丢弃它们。
/*数据消费者*/#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <fcntl.h>#include <limits.h>#include <sys/types.h>#include <sys/stat.h>#define FIFO_NAME "/tmp/my_fifo"#define BUFFER_SIZE PIPE_BUFint main(){ int pipe_fd; int res; int open_mode = O_RDONLY; int bytes_read = 0; char buffer[BUFFER_SIZE + 1]; memset( buffer, '\0', sizeof(buffer) ); printf("Process %d opening FIFO O_RDONLY\n", getpid() ); pipe_fd = open( FIFO_NAME, open_mode ); printf("Process %d result %d\n", getpid(), pipe_fd); if( -1 != pipe_fd ) { do { res = read( pipe_fd, buffer, BUFFER_SIZE ); if( -1 == res ) { fprintf( stderr, "Write error on pipe\n"); exit( EXIT_FAILURE ); } bytes_read += res; }while( res>0 ); close( pipe_fd ); } else exit( EXIT_FAILURE ); printf("Process %d finished, %d bytes read\n", getpid(), bytes_read ); exit( EXIT_SUCCESS );}
程序运行结果
0 0
- 使用 FIFO 实现进程间通信示例
- 进程间通信-FIFO
- 进程间通信--FIFO
- 进程间通信-fifo
- linux进程间的通信(Perl):FIFO应用示例
- EPOLL+FIFO多进程通信简单示例
- 进程间的通信-FIFO
- 进程间通信之FIFO
- 进程间通信(二):FIFO
- 进程间的通信 FIFO
- linux 进程间通信 FIFO
- 进程间通信(IPC):FIFO
- 进程间通信之FIFO
- linux下使用FIFO进行进程间通信
- 使用FIFO来进行两个进程间的通信
- Linux进程间通信: FIFO(1)
- Linux进程间通信: FIFO(2)
- 进程间通信--FIFO管道
- Git common commands summary
- MFC中的运行时类型识别(RTTI)
- java中的多线程
- [CODEFORCES]Good Bye 2014题解
- Java基础----System.in、System.out
- 使用 FIFO 实现进程间通信示例
- 需求:修改指定目录内所有含有某字段文件
- Android内核详解之Low memory killer
- Django引用CSS示例
- dom4j将生成好的doc写入磁盘,并解决中文乱码
- Ubuntu 搭建PHP环境
- 文件目录操作一----------文件复制
- Android Framework 记录
- 黑马程序员——NSArray的基本使用和常见方法的使用