在实现阻塞和非阻塞的名字管道时,我对打开、读、写系统调用有混淆。我感到困惑的是,是什么阻塞了process.open,读还是写。
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);
}我也经历过这个链接
发布于 2014-01-28 19:06:15
如果未指定O_NDELAY或O_NONBLOCK,则FIFO上的打开将阻塞,直到读取器和写入器都出现为止。
但举个例子,如果您将代码更改为:(在Write.c中)
if ((fd=open("fifo", O_RDWR | O_NONBLOCK)) < 0)
{
perror("open");
return;
}它将是非阻塞的
更多信息
https://stackoverflow.com/questions/21413485
复制相似问题