专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 编程

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

发布时间:2011-06-30 11:30:04 文章来源:www.iduyao.cn 采编人员:星星草
使用 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 %sn", FIFO_NAME );
            exit( EXIT_FAILURE );
        }
    }

    printf("Process %d opening FIFO O_WRONLYn", getpid() );
    pipe_fd = open( FIFO_NAME, open_mode );
    printf("Process %d result %dn", 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 pipen");
                exit( EXIT_FAILURE );
            }
            bytes_sent += res;
        }
        close( pipe_fd );
    }
    else
        exit( EXIT_FAILURE );

    printf("Process %d finishedn", 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, '', sizeof(buffer) );
    
    printf("Process %d opening FIFO O_RDONLYn", getpid() );
    pipe_fd = open( FIFO_NAME, open_mode );
    printf("Process %d result %dn", getpid(), pipe_fd);

    if( -1 != pipe_fd ) {
        do {
            res = read( pipe_fd, buffer, BUFFER_SIZE );
            if( -1 == res ) {
                fprintf( stderr, "Write error on pipen");
                exit( EXIT_FAILURE );
            }
            bytes_read += res;
        }while( res>0 );
        close( pipe_fd );
    }
    else
        exit( EXIT_FAILURE );

    printf("Process %d finished, %d bytes readn", getpid(), bytes_read );
    exit( EXIT_SUCCESS );
}

程序运行结果



友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: