mkfifo函数创建有名管道

本文介绍了命名管道(FIFO)的概念及其在不同进程间的通信机制。详细解析了命名管道的打开规则,并通过示例代码展示了如何使用命名管道进行进程间的数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pipe创建的管道只能在具有共同祖先的进程间通信,而mkfifo能在不相关的进程间交换数据。通俗举例来说,一个在一个c文件中通信,一个可在多个c文件中通信。
命名管道打开的规则:
为读打开FIFO:
O_NONBLOCK disable:阻塞直到有相应进程为写而打开FIFO
O_NONBLOCK enable:立刻返回成功
为写打开FIFO:
O_NONBLOCK disable:阻塞直到有相应进程为读而打开FIFO
O_NONBLOCK enable:立刻返回失败,错误码为ENXIO
打开文件描述符默认为阻塞。


管道创建与写管道程序:
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#define SIZE 20

int main( int argc, char **argv )
{
    int fd;

    if( (mkfifo(argv[1], 0666)==-1) && (errno!=EEXIST) )//加后一半可令创建管道后的再次读取不输出错误提示!
    {
        perror( "create fifo error!" );
        exit( -1 );
    }
    if( (fd=open(argv[1], O_WRONLY)) == -1 )
    {
        perror( "open file error!" );
        exit( -1 );
    }
    write( fd, argv[2], SIZE );
    close( fd );
    puts( "write success!" );

    exit( 1 );
}


管道接收程序:
#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<errno.h>
#include<fcntl.h>
#include<stdlib.h>
#define SIZE 20

int main( int argc, char **argv )
{
    int fd;
    char buffer[SIZE];

    if( (fd=open(argv[1], O_RDONLY | O_NONBLOCK)) == -1 )
    {
        perror( "open file error!" );
        exit( -1 );
    }
    while( 1 )
    {
        memset( buffer, 0, SIZE );
        if( read(fd, buffer, SIZE) == -1 )
        {
            perror( "please input something!" );
        }
        else
        {
            printf( "receieve %s!", buffer );
        }
        sleep( 1 );
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值