码迷,mamicode.com
首页 > 系统相关 > 详细

使用 FIFO 实现进程间通信示例

时间:2015-01-01 17:24:25      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:linux   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_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_BUF

int 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 );
}

程序运行结果

技术分享


使用 FIFO 实现进程间通信示例

标签:linux   fifo   进程间通信   

原文地址:http://blog.csdn.net/u014488381/article/details/42319717

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!