使用 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 );
}

程序运行结果

技术分享


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。