有名管道读写

本文提供了一个使用mkfifo创建管道文件并进行读写操作的代码示例。读代码展示了如何打开管道进行阻塞读取,而写代码则演示了如何向管道写入字符串。通过这个例子,读者可以理解管道的基本工作原理及其在进程间通信中的应用。

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

#读代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <errno.h>
int main()
{
 int rfd;
 char str[32];
 printf("读程序\n");
 mkfifo("fifo",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);//管道只能实现单向通信,需创建管道文件
 rfd=open("fifo",O_RDONLY);//只读且阻塞

 /*if(rfd==-1)
 {
     printf("Open file error\n");
     exit(1);
 }*/
 
 while(1)
 {
    
    memset(str,0,sizeof(str));
    if((i=read(rfd,str,sizeof(str)))>0)
        printf("read:%s\n",str);
 }
    close(rfd);
}

#写代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
 int wfd;
 char str[32];
 mkfifo("fifo",S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);           //管道只能实现单向通信,需创建管道文件
 sscanf(argv[1],"%s",str);//编译写入str
 wfd=open("fifo",O_WRONLY);//只写且阻塞
 if(wfd<=0)
  return 0;
 write(wfd,str,sizeof(str));
 close(wfd);
 exit(0);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值