c++之linuxIPC(二)--有名管道(FIFO)

简单说明

有名管道会堵塞,直到被读取

测试代码

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

//int main(int argc,char*argv[])
int main(int argc,char**argv)
{
    if(argc<2)
    {
        printf("argc<2\n");
        return -1;
    }

    for(int i=0;i<argc;i++)
    {
        printf("argv[%d]: %s\n",i,argv[i]);
    }

     char*fifo_name="my_fifo";
     int fd;

    if(strcmp(argv[1],"-write")==0)
    {
        printf("this write mode \n");

        if(access(fifo_name,0)==-1)
        {
            printf("there is not fifo,create it.\n");
            mkfifo(fifo_name,0777);
        }

        
        fd=open(fifo_name,O_WRONLY);
        char*tmp_str="hello,fifo";
        
        write(fd,tmp_str,strlen(tmp_str));
        close(fd);

    }else if(strcmp(argv[1],"-read")==0)
    {
        printf("this read mode \n");

        fd=open(fifo_name,O_RDONLY);
        char buf[32]={0};
        read(fd,buf,32);
        close(fd);

        printf("recv: %s\n",buf);
    }

    return 0;
}

测试结果

[root@localhost myapp]# ./a.out -write
argv[0]: ./a.out
argv[1]: -write
this write mode


[root@localhost myapp]# ./a.out -read
argv[0]: ./a.out
argv[1]: -read
this read mode
recv: hello,fifo


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值