linux创建有名管道程序,linux 下有名管道读写

本文详细介绍了Linux环境下管道操作在阻塞和非阻塞模式下的区别,特别是在读写操作中的行为差异。在阻塞模式下,如果缓冲区无空间或无数据,操作将被阻塞;而非阻塞模式下,无空间写入或无数据可读时,系统将立即返回错误。文中提供测试代码以辅助理解这两种模式的工作原理。
摘要由CSDN通过智能技术生成

在Linux下对管道的操作主要集中于阻塞和非阻塞两种情况下,在这两种情况下的主要区别在于写的情况下,主要区别为:

无论是在阻塞还是非阻塞情况下,read操作总是要先于write 操作之前打开,否则,容易产生错误:No such device or address。

写操作,在阻塞情况下,如果缓冲区空间不存在的话,则会阻塞在write操作中;在非阻塞情况下,如果缓冲区中不存在空间的话,则直接返回错误,EAGAIN(Resource temporarily unavailable);

读操作,在阻塞情况下,如果缓冲区不存在数据的话,则会阻塞在read操作中;在非阻塞情况下,如果缓冲中不存在数据的话,则会直接返回数据长度为0。

附:测试代码;

void sigfuc(int nsig)

{

printf("sigfunc/n");

}

int main(int argc,char** argv)

{

signal(SIGPIPE,sigfuc);

int nfd = -1;

if((nfd = open("pipe",O_WRONLY|O_NONBLOCK)) == -1){

if(errno == ENODEV){

printf("ENOENT/n");

}

printf("%s/n",strerror(errno));

return -1;

}

char szbuf[30]={0};

while (1){

sprintf(szbuf,"----%d/n",time(NULL));

if (write(nfd,szbuf,strlen(szbuf)) < 0)

{

printf("%s/n",strerror(errno));

if (errno == EAGAIN){

printf("No Data Receive./n");

}

printf("read error.../n");

}

else

{

printf("%s/n",szbuf);

}

printf("%s/n",strerror(errno));

}

printf("end/n");

close(nfd);

return 0;

}

int main(int argc,char** argv) {         unlink("pipe");         if(mkfifo("pipe",O_CREAT |O_NONBLOCK |  O_RDWR| 0666) == -1){                 printf("%s/n",strerror(errno));                 return -1;         }         int nfd = -1;         if((nfd = open("pipe",O_RDONLY)) == -1){                 printf("%s/n",strerror(errno));                 return -1;         }         char szbuf[30]={0};         while (1){                 if (read(nfd,szbuf,30) < 0)                 {                         if (errno == EAGAIN){                                 printf("No Data Receive./n");                         }                         printf("read error.../n");                 }                 else                 {                         printf("%s/n",szbuf);                         sleep(5);                 }                 printf("1234567890=%s/n",strerror(errno));         }         printf("end/n");         close(nfd);         return 0; }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值