gpt4 book ai didi

c - 在name pipe open system的情况下是阻塞调用还是读写?

转载 作者:太空狗 更新时间:2023-10-29 12:16:54 27 4
gpt4 key购买 nike

我对阻塞和非阻塞的名称管道实现中的打开,读取和写入系统调用感到困惑。我很困惑哪个正在阻止进程。打开、读取或写入。

1.read.c示例代码

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
main()
{
int ret=0;
int fd=-1;
char buf[BUFSIZ]={0};
fd=open("fifo",O_RDONLY);
if(fd<0)
{
printf("\n mkfifo:%s",strerror(errno));
return;
}
printf("\nFile has open successfully");
while((ret=read(fd,buf,sizeof(buf)/sizeof(buf[0])))>0)
{
printf("\n%s",buf);
memset(buf,0,sizeof(buf)/sizeof(buf[0]));
}
exit(0);
}

2.write.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<string.h>
#include<errno.h>
#include<fcntl.h>
main()
{
int ret=-2;
int fd=-1;
char buf[BUFSIZ]={0};
fd=open("fifo",O_WRONLY);
if(fd<0)
{
printf("\n mkfifo:%s",strerror(errno));
return;
}
printf("\nFile has open successfully");
printf("Enter Message:");
fgets(buf,sizeof(buf)/sizeof(buf[0]),stdin);
ret=write(fd,buf,sizeof(buf)/sizeof(buf[0]));
memset(buf,0,sizeof(buf)/sizeof(buf[0]));
exit(0);
}

我也看过这个链接

How to block the read system call

最佳答案

如果未指定 O_NDELAYO_NONBLOCK,则 FIFO 上的打开会阻塞,直到读取器和写入器都存在。

但是例如,如果您将代码更改为:(在 write.c 中)

  if ((fd=open("fifo", O_RDWR | O_NONBLOCK)) < 0)
{
perror("open");
return;
}

这将是非阻塞的

more info

关于c - 在name pipe open system的情况下是阻塞调用还是读写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21413485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com